Python, Using the enumerate() function: Getting the elements and indices of a list

Money and Business

Using Python's enumerate() function, you can get the index number (count, order) as well as the elements of an iterable object such as a list or tuple in a for loop.

This article explains the basics of the enumerate() function.

  • Function to get the index in a for loop: enumerate()
    • Normal for loop
    • For loop using the enumerate() function
  • Start the index of the enumerate() function at 1 (a non-zero value)
  • Specify the increment (step)

The enumerate() function can be used to get the index in a for loop.

Normal for loop

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

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

For loop using the enumerate() function

Specify an iterable object such as a list as the argument of the enumerate() function.

You can get the index number and the element in that order.

for i, name in enumerate(l):
    print(i, name)
# 0 Alice
# 1 Bob
# 2 Charlie

Start the index of the enumerate() function at 1 (a non-zero value)

As shown in the example above, by default, the index of the enumerate() function starts from 0.

If you want to start with a number other than 0, specify an arbitrary starting number as the second argument of the enumerate() function.

To start from scratch, do the following.

for i, name in enumerate(l, 1):
    print(i, name)
# 1 Alice
# 2 Bob
# 3 Charlie

Of course, you can start with other numbers.

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

Useful when you want to create a sequentially numbered string; it is smarter to specify the starting number as the second argument of the enumerate() function than to use 'i+1' to start from 1.

for i, name in enumerate(l, 1):
    print('{:03}_{}'.format(i, name))
# 001_Alice
# 002_Bob
# 003_Charlie

See the following article for more information about the format function, which is used to fill numbers with zeroes.

Specify the increment (step)

There is no argument to specify the incremental step in the enumerate() function, but it can be achieved by doing the following

step = 3
for i, name in enumerate(l):
    print(i * step, name)
# 0 Alice
# 3 Bob
# 6 Charlie
Copied title and URL