How to Use enumerate() to Print a Numbered List in Python
See Python: Tips and Tricks for similar articles.
You have a list of items and want to print it out as a numbered list using Python.
Starting List
fruit = ['banana', 'apple', 'pear', 'peach']Desired Output
- banana
- apple
- pear
- peach
In another programming language, you might create a variable called i or num and then loop through the list incrementing the variable value by 1 with each iteration.
In Python, you use enumerate():
fruit = ['banana', 'apple', 'pear', 'peach']
for i, item in enumerate(fruit,1):
print(i, '. ' + item, sep='',end='')How enumerate() Works
The enumerate(iterable, start) function will return a sequence of tuples. If we loop through that sequence normally like this, we get a tuple on each iteration:
for t in enumerate(iterable):
print(t) #t is a tupleBut the syntax we showed above unpacks that tuple on each iteration, so:
for a, b in enumerate(iterable):
print(a) #first value in the tuple (the count)
print(b) #second value in the tuple (the item in the original iterable)