python - List.append() under a loop in a list can't get a right ouput -


usually this:

a=[] x in range(5):     a.append(x) print(a) # [0, 1, 2, 3, 4] 

then put loop in list

a=[] l=[a.append(x) x in range(5)] print(l) # [none, none, none, none, none] 

i don't konw what's wrong it...

the problem here a.append(x) method of list a modifies a in place. returns none.

interestingly this:

a=[] l=[a.append(x) x in range(5)] print(l) # [none, none, none, none, none] print(a) # [0, 1, 2, 3, 4] 

note a updated. however, using list comprehensions side effects not recommended since code becomes hard understand.

if want create l using list comprehension should this:

l = [x x in range(5)] print(l) # [0, 1, 2, 3, 4] 

the best code hovever simply

l = list(range(5)) print(l) # [0, 1, 2, 3, 4] 

Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -