This (creating an extra variable before the for-loop) is not pythonic .
The pythonic way to iterate over items while having an extra counter is using enumerate:
for index, item in enumerate(iterable): print(index, item)So, for example for a list lst this would be:
lst = ["a", "b", "c"] for index, item in enumerate(lst): print(index, item)...and generate the output:
0 a 1 b 2 cYou are strongly recommended to always use Python's built-in functions for creating "pythonic solutions" whenever possible. There is also the documentation for enumerate.
If you need more information on enumerate, you can look up PEP 279 -- The enumerate() built-in function.
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.
Copied!
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) # 👉️ 3The 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.
Copied!
my_list = ['a', 'b', 'c'] for index, item in enumerate(my_list): print(index, item) # 👇️ # 0 a # 1 b # 2 cThe 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().
Copied!
my_list = ['a', 'b', 'c'] for count, item in enumerate(my_list, start=1): print(count, item) # 👇️ # 1 a # 2 b # 3 cThe 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:
- Initialize a count variable and set it a number.
- Use a for loop to iterate over a sequence.
- On each iteration, reassign the count variable to its current value plus N.
Copied!
my_list = ['a', 'b', 'c'] count = 0 for item in my_list: count += 1 print(count) print(count) # 👉️ 3We 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.
Copied!
my_list = ['a', 'b', 'c'] count = 0 for item in my_list: count = count + 1 print(count) print(count) # 👉️ 3