It is very common for me to loop through a python list to get both the contents and their indexes. What I usually do is the following:
S = [1,30,20,30,2] # My list
for s, i in zip(S, range(len(S))):
# Do stuff with the content s and the index i
I find this syntax a bit ugly, especially the part inside the zip
function. Are there any more elegant/Pythonic ways of doing this?
enumerate()
makes this prettier:
for index, value in enumerate(S):
print index, value
See here for more.
enumerate
is what you want:
for i, s in enumerate(S):
print s, i
>>> for i, s in enumerate(S):
Like everyone else:
for i, val in enumerate(data):
print i, val
but also
for i, val in enumerate(data, 1):
print i, val
In other words, you can specify as starting value for the index/count generated by enumerate() which comes in handy if you don't want your index to start with the default value of zero.
I was printing out lines in a file the other day and specified the starting value as 1 for enumerate()
, which made more sense than 0 when displaying information about a specific line to the user.
Use enumerate()
:
>>> S = [1,30,20,30,2]
>>> for index, elem in enumerate(S):
print(index, elem)
(0, 1)
(1, 30)
(2, 20)
(3, 30)
(4, 2)
Source: Stackoverflow.com