How to count in a for loop in Python

avatar

Borislav Hadzhiev

Last updated: Jul 3, 2022

banner

Check out my new book

Count in a for loop in Python #

Use the enumerate() function to count in a for loop, e.g. for index, item in enumerate(my_list):. The function takes an iterable and returns an object containing tuples, where the first element is the index, and the second - the item.

main.py
my_list = ['a', 'b', 'c'] # ✅ count in for loop for index, item in enumerate(my_list): print(index, item) # 👇️ # 0 a # 1 b # 2 c # --------------------------------------------- # ✅ count in for loop starting with N for count, item in enumerate(my_list, start=1): print(count, item) # 👇️ # 1 a # 2 b # 3 c # ---------------------------------------------- # ✅ manually incrementing counter in for loop counter = 0 for item in my_list: counter += 1 print(counter) print(counter) # 👉️ 3

The enumerate function takes an iterable and returns an enumerate object containing tuples where the first element is the index, and the second - the item.

We can directly unpack the index (or count) and the item in our for loop.

main.py
my_list = ['a', 'b', 'c'] for index, item in enumerate(my_list): print(index, item) # 👇️ # 0 a # 1 b # 2 c

The enumerate function takes an optional start argument, which defaults to 0.

If you need to start the count from a different number, e.g. 1, specify the start argument in the call to enumerate().

main.py
my_list = ['a', 'b', 'c'] for count, item in enumerate(my_list, start=1): print(count, item) # 👇️ # 1 a # 2 b # 3 c

The count variable has an initial value of 1 and then gets incremented by 1 on each iteration.

Alternatively, you can manually count in the for loop.

To count in a for loop:

  1. Initialize a count variable and set it a number.
  2. Use a for loop to iterate over a sequence.
  3. On each iteration, reassign the count variable to its current value plus N.
main.py
my_list = ['a', 'b', 'c'] count = 0 for item in my_list: count += 1 print(count) print(count) # 👉️ 3

We declared a count variable and initially set it to 0.

On each iteration, we use the += operator to reassign the variable to its current value plus N.

The following 2 lines of code achieve the same result:

  • count += 1
  • count = count + 1

Here is an example that uses the longer reassignment syntax.

main.py
my_list = ['a', 'b', 'c'] count = 0 for item in my_list: count = count + 1 print(count) print(count) # 👉️ 3
Use the search field on my Home Page to filter through my more than 3,000 articles.