0
x  = 0

y = []

for i in range (5):
    y.append(x)
    x+=1

print y

Gives:

[0, 1, 2, 3, 4]

But,

x  = range (2)

y = []

for i in range (5):
    y.append(x)
    x[0]+=1

print y

I would have thought (hoped) that this gives me:

[[0, 1], [1, 1], [2, 1], [3, 1], [4, 1]]

But instead it just gives me:

[[5, 1], [5, 1], [5, 1], [5, 1], [5, 1]]

I've tested it by putting 'print y' inside the for loop, and obviously what is happening is that when x[0]+=1, all the 'x's that are already inside 'y' are being updated with the new value.

How do I write the program so that it 'forgets' that the 'x's already in list 'y' are still variables (and so doesn't keep updating them)?

I've realized I could just write this one specifically as:

y = []

for i in range (5):
    x = [i, 1]
    y.append(x)

But what if I wanted to define x outside of the for loop? I can't think of a time when I would want to do it this way but I just want to know anyway.

1
  • 1
    "How do I write the program so that it 'forgets' that the 'x's already in list 'y' are still variables" - this makes no sense. Pyton doesn't really have "variables", it has names that are references to objects (see e.g. nedbatchelder.com/text/names.html). You fill y with multiple references to the same list. To fix it, copy; y.append(x[:]). Commented Dec 8, 2014 at 22:54

2 Answers 2

2

@tzaman gives the perfect solution, but you want your own code:

x  = range (2)

y = []

for i in range (5):
    y.append(x[:]) #You should append copy of x
    x[0]+=1

print y

gives:

[[0, 1], [1, 1], [2, 1], [3, 1], [4, 1]]
Sign up to request clarification or add additional context in comments.

2 Comments

or just append(range(2))
Thanks, I'll try this one. tzaman's solution was alright but not really what I was asking, so this one's better.
2

If you define x outside the for loop, it's a reference to the same list every time. If you want each sub-list to be independent you have to create it inside the loop. Your final code-block works.

However, a more concise and pythonic way of doing what you want is a list comprehension:

y = [[i, 1] for i in range(5)]

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.