Python index list by tuple
enumerate() in Python: Get the element and index from a listPosted: 2020-08-27 / Tags: Python, List Tweet In Python, you can get the element and index (count) from iterable objects such as lists and tuples in a for loop by the built-in function enumerate(). Show
This article describes the basics of enumerate().
See the following articles for more information about for loop and how to use enumerate() and zip() together.
Sponsored Link How to use enumerate()Normal for loopl = ['Alice', 'Bob', 'Charlie']
for name in l:
print(name)
# Alice
# Bob
# Charlie
source: enumerate_start.py for loop with enumerate()By passing an iterable object in the argument of enumerate(), you can get index, element. for i, name in enumerate(l):
print(i, name)
# 0 Alice
# 1 Bob
# 2 Charlie
source: enumerate_start.py Start index from 1 with enumerate()As in the example above, by default the index of the enumerate() starts from 0. If you want to start from another number, pass it in the second argument of the enumerate(). Example starting from 1: for i, name in enumerate(l, 1):
print(i, name)
# 1 Alice
# 2 Bob
# 3 Charlie
source: enumerate_start.py Example starting from the other number: for i, name in enumerate(l, 42):
print(i, name)
# 42 Alice
# 43 Bob
# 44 Charlie
source: enumerate_start.py For example, this is useful when generating a serial number string. It is smarter to pass the starting number in the second argument of the enumerate() than to calculate i + 1. for i, name in enumerate(l, 1):
print('{:03}_{}'.format(i, name))
# 001_Alice
# 002_Bob
# 003_Charlie
source: enumerate_start.py Sponsored Link Set step with enumerate()There is no argument like step to specify increment to enumerate(), but it can be done as follows. step = 3
for i, name in enumerate(l):
print(i * step, name)
# 0 Alice
# 3 Bob
# 6 Charlie
source: enumerate_start.py Sponsored Link Share TweetRelated Categories
Related Articles
|