Python is amazing.

My understanding so far is that all programming languages can do, at the fundamental level, pretty much the same things - they just all do it in their own way.

And Python has some really unique ways of doing regular things. These are so unique to Python, they even received their own term - writing pythonic code.

One of these features is iteration.

When you need to access both the item and its index, traditionally you would loop over the length of the list and use index to access the item.

1
2
3
4
5

numbers = [1, 2, 3, 4]

for i in range(len(numbers)):
    print(i, numbers[i])

While it works, a more pythonic and cleaner way to do the same thing is to use the enumerate() function, which returns a tuple and lets you access both the index and the item directly.

1
2
3
4
5

numbers = [1, 2, 3, 4]

for i, num in enumerate(numbers):
     print(i, num)

Using enumerate() function makes the code cleaner and more readable.

I’m using enumerate() very often, especially when I’m debugging and I want to clearly see what’s going as it prints very clearly the index of the item and the item itself.