The following is totally bogus code. But let's say you needed to do some extra side effecting function calls (for debugging to logs)? How would you put that in?
[ i for i in range(10) ]
Or does one always have to rewrite as a normal for loop?
list=[]
for i in range(10):
otherStuff()
list.append(i)
In C, there is a comma operator for such things...
Plainly, don't use side-effects in list comprehensions. It makes your code incredibly unclear to the next person who has to maintain it, even if you understand it perfectly. List comprehensions are a succinct way of creating a list, not a way to call a function n times.
For further reading, see the question Is it Pythonic to use list comprehensions for just side effects?
In other words, you should use an explicit for loop for that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With