loading...

March 24, 2016

Common Python Iteration Mistakes

List Enumeration

We have a lot of Java programmers moving over to the Python side of the fence lately, and I’ve been seeing a lot of non-pythonic code reviews in the realm of iteration collections. For instance, sometimes we want to iterate a list or array while operating with both an object and an index. I’ve seen both of the following behaviors.

Iterate over the list while maintaining an index:

index = 0
for data in my_list:
    print(index, data)
    data += 1

Iterate over index while accessing the list data:

for index in range(len(my_list)):
    data = my_list[index]
    print(index, data)

This common use case presents two ways of doing the same thing, which is largely disliked in the Python community. Which is why the enumerate function is built into the language:

for (index, data) in enumerate(my_list):
    print(index, data)

Dictionary Enumeration

The common non-pythonic dictionary enumeration is a bit more common, especially from the really old school Java people.

The Wrong Way

for key in my_dict:
    value = my_dict[key]
    print(key, value)

The Right Way

for (key, value) in my_dict.iteritems():
    print(key, value)
Posted in Python
Write a comment