+ 1

List in a for Loop

I have a question. Imagine a for loop like this: list = ['a', 'b', 'c'] for i in list: print list.index(i) This would give me: 0 1 2 But how can I get the indices of a list in this kind of loop, if I don't assign it beforehand to an list variable. Like this: for i in ['a', 'b', 'c'] print ????

17th Jan 2017, 10:54 PM
martin
1 Réponse
+ 1
for index, _ in enumerate(['a', 'b', 'c']): print(index) The enumerate function lets you iterate over the indices and the collection at the same time. It is very useful in some cases, and your example is perfect for that. Indeed, imagine your list is ['a', 'a', 'a']. Your code would output 0 0 0, instead of 0 1 2. Depends on what you want, but it is a real ease to use enumerate.
18th Jan 2017, 8:52 PM
Amaras A
Amaras A - avatar