Rich Rich - 6 months ago 11
Python Question

Simple ieteration/append loop not returning correct array:

I have a six-line section of code:

setA = 101

for i in range(101):
l = [0]
q = i * 3
f = str(q)
print f


That prints the numbers upwards:

0
3
6
9
12
15
18
21
24
27
30
33


But I want them in an array, and so I changed it:

setA = 101

for i in range(101):
l = [0]
q = i * 3
f = str(q)
l.append(f)

print str(l)


But now, it only gives me a two-value array
[0, '300']
, and that's it. I have a feeling that I'm missing something really, really basic. Can anyone clarify?

Answer

You're resetting your array with each iteration:

for i in range(101):
    l = [0]

Move that out of your loop and it'll work:

l = []
for i in range(101):
    q = i * 3
    f = str(q)
    l.append(f)

print str(l)