note.nkmk.me

enumerate() in Python: Get the element and index from a list

Posted: 2020-08-27 / Tags: Python, List

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().

This article describes the basics of enumerate().

  • How to use enumerate()
    • Normal for loop
    • for loop with enumerate()
  • Start index from 1 with enumerate()
  • Set step with 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 loop

l = ['Alice', 'Bob', 'Charlie']

for name in l:
    print(name)
# Alice
# Bob
# Charlie

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

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

Example starting from the other number:

for i, name in enumerate(l, 42):
    print(i, name)
# 42 Alice
# 43 Bob
# 44 Charlie

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
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
Sponsored Link
Share

Related Categories

Related Articles