etienne haddad
etienne haddad

Reputation: 29

For-loop only returns last value

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?

Upvotes: 0

Views: 2591

Answers (1)

chepner
chepner

Reputation: 531165

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)

Upvotes: 3

Related Questions