Use the enumerate()
function:
for i, item in enumerate(items):
print i, item
or use range()
:
for i in range(len(items)):
print i
(On python 2 you'd use xrange()
instead).
range()
let's you step through i
in steps other than 1
as well:
>>> list(range(0, 5, 2))
[0, 2, 4]
>>> list(range(4, -1, -1))
[4, 3, 2, 1, 0]
You usually don't need to use an index for sequences though; not with the itertools
library or the reversed()
function; most usecases for 'special' index value ranges are covered:
>>> menu = ['spam', 'ham', 'eggs', 'bacon', 'sausage', 'onions']
>>> # Reversed sequence
>>> for dish in reversed(menu):
... print(dish)
...
onions
sausage
bacon
eggs
ham
spam
>>> import itertools
>>> # Only every third
>>> for dish in itertools.islice(menu, None, None, 3):
... print(dish)
...
spam
bacon
>>> # In groups of 4
>>> for dish in itertools.izip_longest(*([iter(menu)] * 4)):
... print(dish)
...
('spam', 'ham', 'eggs', 'bacon')
('sausage', 'onions', None, None)