Modifying List Entries in a Python Loop

Python does not have a for loop in the classic sense. It’s for loop feels like for-each constructs provided by other languages. So today when I had to modify the contents of a list in a loop, I looked around for the best way to do this. This lead me to this StackOverflow question.

There was a little discussion that happened in the comments section. I thought I would weigh in. There were three proposed answers:

  1.  Using list comprehensions: Python provides a quick, but ugly way of creating new lists from existing ones. This solution is simple.

    I for one have mixed feelings about this. It works, it quick. But not really readable. It may be a ‘Pythonic’ solution, but looks extremely ugly with more complex operations. Suppose I add an if statement

    Now that is just ugly. So I decided to move on.
  2. Using Python’s enumerate method: This returns a key/value pair. As an added bonus this works with dictionaries as well.

    But this is not the cleanest code. As someone who works on Python occasionally, I find it a little complex for something that could have been easier.
    EDIT: After using Python for a while, I’ve gotten accustomed to this. Stockholm syndrome? Maybe.
  3.  Using Python’s version of a classic for loop: This makes use of Python’s range() method to iterate over the whole length of the list.

    This is my personal favorite, as it is the most readable option. And additionally it looks similar to C based languages (personal bias maybe).

So you could go with the enumerate() method or the classic for loop. But a list comprehension is best avoided in this case.

Adarsh

Howdy! You're reading my blog. To know more about me click here

Leave a Reply

Your email address will not be published. Required fields are marked *