0

The code below:

rect_pos = {}

rect_pos_single = [[0,0], [50, 0], [50, 100], [0, 100]]

i = 0

while (i<3): 

    for j in range(4):

        rect_pos_single[j][0] += 50

    print rect_pos_single

    rect_pos[i] = rect_pos_single

    i += 1

print rect_pos

The code prints subsequent iterations of the variable "rect_pos_single". Next, I add them to dictionary "rect_pos". Keys change, but value is always the same - last iteration. I do not understand why?

1
  • Have you tried extracting the element from the dictionary, performing the addition, and then re-adding it to the dictionary? What is your expected output? And what is your current output? Commented Apr 29, 2014 at 13:14

1 Answer 1

1

This line

rect_pos_single[j][0] += 50

modifies the list in-place; that is, rect_pos_single always refers to the same list object, but you change the contents of that list.

This line

rect_pos[i] = rect_pos_single

assigns a reference to the list referenced by rect_pos_single to rect_pos[i]. Each element of rect_pos refers to the same list.

The simplest change is to assign a copy of the list to the dictionary with

rect_pos[i] = copy.deepcopy(rect_pos_single)  # Make sure you import the copy module

A deep copy is needed because rect_pos_single is a list of lists, and doing a shallow copy with rect_pos_single would simply create a new list with references to the same lists that are actually modified with rect_pos_single[j][0] += 50.

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

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.