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:
- Using list comprehensions: Python provides a quick, but ugly way of creating new lists from existing ones. This solution is simple.
1234list = [1, 3, 5]list[:] = [x + 2 for x in list]
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
1234list = [1, 3, 5]list[:] = [x + 2 for x in list if x > 2]
Now that is just ugly. So I decided to move on.
- Using Python’s enumerate method: This returns a key/value pair. As an added bonus this works with dictionaries as well.
1234for key, value in enumerate(list):a[key] = value + 2
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.
- 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.
1234for i in range(0, len(list)):list[i]= list[i] + 2
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.