1

I tried to use append with multiple lists at the same time (in a continual line).

However, it added all the items to all of my lists. Please see the script and result below:

x1=y1=z1=[]
for i in range(1,5):
    x1.append(i)
    y1.append(i*4)
    z1.append(i*10)
print ("\n x1=", x1,"\n y1=", y1,"\n z1=", z1)

Result:

 x1= [1, 4, 10, 2, 8, 20, 3, 12, 30, 4, 16, 40] 
 y1= [1, 4, 10, 2, 8, 20, 3, 12, 30, 4, 16, 40] 
 z1= [1, 4, 10, 2, 8, 20, 3, 12, 30, 4, 16, 40]

Thanks for your comment.

3 Answers 3

4

That's because x1, x2 and x3 binds to the same list. Write x1, x2, x3 = [], [], [] instead of x1 = x2 = x3 = [].

Sign up to request clarification or add additional context in comments.

Comments

1

This is because all your list variables are pointing to the same list.

Initialize your lists as follows instead:

x1 = []
y1 = []
z1 = []

Doing, x1 = y1 causes both these variables to point to the same memory space and so modifying one makes it look like you are modifying all of them when in fact they are all just the same thing

Comments

0

If you are only interested in the output, you can do a more pythonic approach using list comprehensions:

print [i for i in range(1,5)]
print [i*4 for i in range(1,5)]
print [i*10 for i in range(1,5)]

Or if you want to keep the values then do:

x1 = [i for i in range(1,5)]
y1 = [i*4 for i in range(1,5)]
z1 = [i*10 for i in range(1,5)]
print ("\n x1=", x1,"\n y1=", y1,"\n z1=", z1)

Or if you really want to shrink your code, you could do this:

for j in zip(*[[i,i*4,i*10] for i in range(1,5)]): print j

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.