I am trying this code on python:
N = 5
for n in xrange (0, N):
a = [10 + n]
print(a[0])
The code returns 14
, and when I try to print(a[1])
I have a list index error. What I want is to be able to view a[0]
, a[1]
... a[n]
. When I write a=[10 + n for n in xrange (0,N)]
it works but I don't understand the difference. Can anyone help on how to make the first method work?
You aren't appending to a list; you are repeatedly redefining which single-element list a
refers to.
a = []
for n in range(N):
a.append(10 + n)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.