Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python adding additional code to inline for loops?

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...

like image 337
Chris Avatar asked Dec 28 '25 13:12

Chris


1 Answers

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.

like image 168
Adam Smith Avatar answered Dec 31 '25 05:12

Adam Smith