Photo by Oliver Hale on Unsplash
Python’s for
statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.
Looping techniques
When looping through a sequence like a list, tuple, range object, strings the position index and corresponding value can be retrieved at the same time using the enumerate()
function.
**enumerate**(_iterable_, _start=0_)
Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The
_ __next__()_
method of the iterator returned by_enumerate()_
returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable.
Looping through the list using enumerate():
Example 1:
Looping through the list using the enumerate() function returns a tuple containing count and value from the iterable. By default, the count starts from 0
.
l=['red','green','blue']
for i in enumerate(l):
print (i)
#Output:
(0, 'red')
(1, 'green')
(2, 'blue')
Example 2:
l=['red','green','blue']
for i,j in enumerate(l):
print (i,j)
#Output:
0 red
1 green
2 blue
Example 3:
The start is mentioned as 5. So count starts from 5 while looping through the iterable.
li=['red','green','blue']
for i in enumerate(li,5):
print (i)
#Output:
(5, 'red')
(6, 'green')
(7, 'blue')
#python3 #python-programming #python #looping-python