Python tip 27: enumerate() function
When you use a for
loop, you get one element per each iteration. If you need the index of the elements as well, use the enumerate() built-in function. You'll get a tuple
value per each iteration, containing index (starting with 0
by default) and the value at that index.
>>> nums = [42, 3.14, -2, 1000]
>>> for t in enumerate(nums):
... print(t)
...
(0, 42)
(1, 3.14)
(2, -2)
(3, 1000)
>>> names = ['Jo', 'Joe', 'Jon']
>>> [(n1, n2) for i, n1 in enumerate(names) for n2 in names[i+1:]]
[('Jo', 'Joe'), ('Jo', 'Jon'), ('Joe', 'Jon')]
By setting the start
argument, you can change the initial value of the index.
>>> items = ('car', 'table', 'book')
>>> for idx, val in enumerate(items, start=1):
... print(f'{idx}: {val}')
...
1: car
2: table
3: book
Video demo:
See also my 100 Page Python Intro ebook.