Reputation: 61
I am trying to append elements into empty list. using list.append() method. script gives recent value, But not appending to list.
I have tried below script it is giving updated value.
for i in range(10):
x = []
if i > 1:
x.append(i)
print (x)
Output : [9]
Expected output : [2, 3, 4, 5, 6, 7, 8, 9]
Could you please help me why i am getting this output and how to resolve it?
Upvotes: 0
Views: 166
Reputation: 7313
You should not create new list in every iteration because it replaces the old data with a new list:
x = []
for i in range(10):
if i > 1:
x.append(i)
print (x)
However, there is a simpler way to do this:
[i for i in range(10) if i > 1]
Output:
[2, 3, 4, 5, 6, 7, 8, 9]
Upvotes: 2