简体   繁体   中英

Why does assiging a list element to a variable work in a different manner here?

I have this piece of code:

lst = [[1,1], [2,1],[3,1]]
n = len(lst)
head = lst[n - 1]

head[0] += 1

lst.append(head)
del lst[0]

print(lst)

And I'm expecting this code to print: [[2,1], [3,1], [4,1]] But it's printing: [[2, 1], [4, 1], [4, 1]]. I don't understand why. Please help me.

When you write head = lst[n - 1] , that sets head to the last element of lst by reference. This means that the pair with values [3,1] is shared by both variables. If you want to not alter the pair in the original list, make sure that head copies the data.

head = lst[n - 1].copy()

A quick fix for your need is

inc_lst = [ [ x[0]+1 , x[1] ] for x in lst]

Hopefully it will help

When you use

head = lst[n - 1]

you got reference [3,1] as head, when you execute

head[0] += 1

you changed [[1,1], [2,1], [3,1]] to [[1,1],[2,1], [4,1]]

When you make append, lst got another copy of head.

Therefore, after del lst[0], you got the result [[2,1], [4,1], [4,1]]

  1. lst = [[1,1], [2,1],[3,1]]
  2. n = len(lst) - n will be equal 3
  3. head = lst[n - 1] => head = lst[2] => head = [3, 1]
  4. head[0] += 1 it change head, head = [4, 1]
  5. lst.append(head) , remember lst = [[1, 1], [2, 1], [4, 1]] and head = [4, 1] => [[1, 1], [2, 1], [4, 1], [4, 1]]
  6. del lst[0] => [[2, 1], [4, 1], [4, 1]]

Anyway, when head was [3, 1] then you change head and it automatically change lst[n - 1]

Also, please try using http://www.pythontutor.com/visualize.html

A very useful tool if need to understand how code works step by step.

It's actually a very common problem among beginners in programming (such as myself). The other questions already answered the question, but I just wanted to mention that this is a case of "value semantics vs reference semantics". It can be usefull to shortly read up on this topic in order to avoid this kind of mistakes in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM