Indexing
“Indexing” means addressing an element of a sequential object by its position within the sequential object. A sequential object is in general, an ordered collection. In python, every element of an ordered collection is accessed based on their position in the collection. An index is a numerical form of position. Python uses square bracket notation[] to index collections. An index of elements in a collection ranges between [0 ] to [len(collection)-1], other values will give IndexError.
#indexing in list list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'] list[0] #Output: 'a' #indexing in string str = "Python" str[5] #Output: 'n' #indexing in tuple tup = (1,2,3,4,5,6,7,8,9) tup[5] #Output: 6
Dictionaries in python are an unordered collection of key : value pairs. In dictionaries, related information is associated with keys. Even though dictionaries are unordered, their values can be accessed by their keys.
dict = { "fruit": "Mango", "season": "Summer", "colour": "yellow" } #indexing through position dict[0] #Output: KeyError: 0 #indexing through key dict["colour"] #Output: "yellow"
Python allows negative indexing i.e. indexing from the end of the list using a negative number. Negative index of a collection ranges between [-1] to [-len(collection)].
#negative indexing in list list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'] list[-1] #Output: 'i' #negative indexing in string str = "Python" str[-6] #Output: 'P' #negative indexing in tuple tup = (1,2,3,4,5,6,7,8,9) tup[-5] #Output: 5
Iterating
“Iterating” or “looping” means repeating the execution of a similar task. Python for loop statement loops over iterables to execute the same block of code again and again. An iterable is an object which can return its element one by one. Sequences are ordered sets of iterables that have specific set of features. Lists, tuples, and strings are all sequences. Apart from sequences, collections like sets and dictionaries are also built-in iterables in python. File objects and generators are other iterables in python.
To manually iterate through the items of an iterable object iter() and next() built-in methods are used. An iterator is an actual iterable object that is iterated. The iter() function creates an iterator object. A repeated passing of iterator to the next() function returns successive items in the iterable. If no more elements are available in the iterable then a StopIteration exception is raised.
#iterating through list l = [1,2,3,4] iter_list = iter(l) print(iter_list) print(next(iter_list)) print(next(iter_list)) print(next(iter_list)) print(next(iter_list)) #Output: <list_iterator object at 0x7f7684bf0ee0> 1 2 3 4 #iterating through tuple t = ('a','b','c') iter_tuple = iter(t) print(next(iter_tuple)) print(next(iter_tuple)) print(next(iter_tuple)) #Output: a b c #iterating through string s = "Python" iter_str = iter(s) print(next(iter_str)) print(next(iter_str)) print(next(iter_str)) print(next(iter_str)) print(next(iter_str)) print(next(iter_str)) #Output: P y t h o n #iterating through dictionary dict = {'a':1,'b':2,'c':3,'d':4} iter_dict = iter(dict) print(next(iter_dict)) print(next(iter_dict)) print(next(iter_dict)) print(next(iter_dict)) #Output: a b c d #iterating through set set = {10,20,30,40,50} iter_set = iter(set) print(next(iter_set)) print(next(iter_set)) print(next(iter_set)) print(next(iter_set)) print(next(iter_set)) print(next(iter_set)) #Output: 10 20 30 40 50 StopIteration
Python for loops automatically iterates through the items of an iterable object, executing the block of code each time. The for loop creates an iterator object and executes the next() method over and over until a StopIteration exception is raised which is internally caught and the loop ends. Iterating through iterators using for loop does not require indexes of iterables they directly iterate through each item of iterables using in operator.:
for element in iterable:
#block of code
#iterating through list l = [1,2,3,4] for i in l: print(i) #Output: 1 2 3 4 #iterating through tuple t = ('a','b','c') for j in t: print(j) #Output: a b c #iterating through string s = "Python" for k in s: print(k) #Output: P y t h o n #iterating through set set = {10,20,30,40,50} for x in set: print(x) #Output: 10 20 30 40 50 #iterating through dictionary dict = {'a':1,'b':2,'c':3,'d':4} print("Iterating through dictionary keys only") for key in dict: print(key) print("Iterating through dictionary values only") for value in dict.values(): print(value) print("Iterating through dictionary key:value pair") for key,value in dict.items: print(key,":",value) #Output: Iterating through dictionary keys only a b c d Iterating through dictionary values only 1 2 3 4 Iterating through dictionary key:value pair a : 1 b : 2 c : 3 d : 4
Enumerating
“Enumerating” basically means looping over iterators and getting both value and index of each item of the sequence. A lot of times when working with iterators, there’s a need to keep a count of the number of iterations, or many new programmers needs to know both values and indexes of each element of iterators for better understanding of programming, so enumeration can be used. Enumeration is mainly used by professionals or beginners for creating a dictionary as it returns keys as well as values.
The traditional programming way to do enumeration is by using loops.
#enumerating list l = [1,2,3,4] for i in range(len(l)): print(i,l[i]) #Output: 0 1 1 2 2 3 3 4 #enumerating tuple t = ('a','b','c') for i in range(len(t)): print(i,t[i]) #Output: 0 a 1 b 2 c #enumerating string s = "Python" for c in range(len(s)): print(c,s[c]) #Output: 0 P 1 y 2 t 3 h 4 o 5 n #enumerating set set = {0,10,20,30,40} for i in range(len(set)): print(i,set[i]) #Output: 0 0 1 10 2 20 3 30 4 40 #enumerating dictionary dict = {1:'a',2:'b',3:'c',4:'d',5:'e'} for i in range(len(dict)): print(i,dict[i]) #Output: KeyError
Dictionary is a key : value pair collection. Values of the dictionary are referred by its keys, not by indexes. Thus this method can’t be used to enumerate a dictionary.
Apart from the above method, Python offers a simple built-in function enumerate(), which can not only iterate over the index of an item, as well as the item itself but also makes a program look cleaner. The enumerate() function assigns an index to each item in an iterable object and returns it in the form of an enumerate object. The enumerate method is an iterator that produces a tuple of the form (index, element) for each element. This enumerate object can then be used directly in for loops or be converted into a list of tuples using list() method. The syntax of enumerate() is:
enumerate(iterable, start=0)
In enumerate(), counting starts from start and by default, its value is 0.
s = "Python" enum = enumerate(s) print(enum) print(list(enum)) #Output: <enumerate object> [(0, 'P'), (1, 'y'), (2, 't'), (3, 'h'), (4, 'o'), (5, 'n')]
s = "Python" for item in enumerate(s): print(item) #Output: (0,'P') (1,'y') (2,'t') (3,'h') (4,'o') (5,'n')
Each tuple produced by the enumerated object can be unpacked to two different variables representing index and element.
- Read more on tuple unpacking: http://betapython.com/dictionary-and-tuple-in-python-difference-in-properties/
#enumerate a list l = [1,2,3,4] for i, ele in enumerate(l): print(i,ele) #Output: 0 1 1 2 2 3 3 4 #enumerate a tuple t = ('a','b','c') for i, ele in enumerate(t,1): print(i,ele) #Output: 1 a 2 b 3 c #enumerate a string s = "Python" for i, ch in enumerate(s,1): print(i,ch) #Output: 1 P 2 y 3 t 4 h 5 o 6 n #enumerate a set set = {0,10,20,30,40} for i, ele in enumerate(set): print(i,ele) #Output: 0 0 1 10 2 20 3 30 4 40 #enumerate a dictionary dict = {1:'a',2:'b',3:'c',4:'d',5:'e'} print("enumerate a dictionary") for key, value in dict.items(): print(key,value) print("enumerate dictionary keys") for i, key in enumerate(dict,1): print(i,key) print("enumerate dictionary values") for i, value in enumerate(dict,1): print(i,value) print("enumerate dictionary key:value pairs") for i, item in enumerate(dict.items()): print(i,item) #Output: enumerate a dictionary 1 a 2 b 3 c 4 d 5 e enumerate dictionary keys 1 1 2 2 3 3 4 4 5 5 enumerate dictionary values 1 a 2 b 3 c 4 d 5 e enumerate dictionary key:value pairs 0 (1, 'a') 1 (2, 'b') 2 (3, 'c') 3 (4, 'd') 4 (5, 'e')
Tags: enumerating, enumerating in python, indexing, indexing different data types, indexing in python, iterating, iterating and enumerating in python?, iterating in python, iterating through different data types, negative indexing in python, uses of enumeration, What is indexing, enumerate(), enumerate() in python, enumerating different data types, enumerating different iterators, enumerate different iterators