python - Is it possible to alter an external variable in a list comprehension? -
for instance:
n = 0 = [n=n+1 x in range(1,(12*8)+1) if x % 2 == 0]
this silly question, don't have real use this. use or while loop achieve similar. i'm interested if possible. (which assume it's not haha.)
you cannot make assignments within list comprehension bodies. language specification allows expressions. however, means can call methods have side effects. example, call list.append
modify different list, e.g.
>>> lst = [] >>> [lst.append(i) in range(5)] [none, none, none, none, none] >>> lst [0, 1, 2, 3, 4]
but useful, , of times ends in more confusing expression. it’s far more recommended split standard loop then; avoids overhead of generated list.
Comments
Post a Comment