简体   繁体   中英

Do I need to use list() to append a list into another list in Python?

I am trying to append small ( num ) lists to a final list ( lst ). The small lists are modified in a loop and at each modification they are appended to the final list. But the result is strange and I did not like the solution. Here is the code.

n   = 3
num = []
lst = []

for i in range(n) :
    num.append(0)

lst.append(num)

for j in range(n-1) :
    for i in range(n) :
        num[i] += 1
        lst.append(num)

for each in lst :
    print each

The result of this code is:

[2, 2, 2]
[2, 2, 2]
[2, 2, 2]
[2, 2, 2]
[2, 2, 2]
[2, 2, 2]
[2, 2, 2]

However, if instead of using lst.append(num) , I use lst.append(list(num)) , I get the expected result:

[0, 0, 0]
[1, 0, 0]
[1, 1, 0]
[1, 1, 1]
[2, 1, 1]
[2, 2, 1]
[2, 2, 2]

Is this really the correct way for appending values of a list to another list?

UPDATE: I see that when I do lst.append(num) this does not mean that the values of num are appended to lst . It is a reference and because I change the content of num , in the end, all entries of my list lst will reference to the final num . However, if I do this:

lst = []

for i in range(3) :
    num = i
    lst.append(num)

for each in lst :
    print each

I get what is expected, ie, a list lst with the values [0, 1 , 2]. And in this case, num is changed at every iteration and its final value is num =2.

Lets have a closer look at this loop.

for i in range(n) :
     num[i] += 1
     lst.append(num)

You are appending same num multiple times. So, all elements of lst has the same reference to list num and you are updating it at each iteration. That is why you are getting same value at each element of lst after the loop has completed.

But, when you are doing lst.append(list(num)) , you are generating a new list each time. So, each element of lst has different reference. And you are getting expected output.

So, to answer your question, the way you are adding a list to a list is fine. That is how you should do it. It has nothing to do with your expected outcome.

I think the explanation for your result is that when you do num[i] += 1 you are actually modifying the preceding copies of num that were appended in lst at previous stages of the loop. When you do lst.append(list(num)) you are creating a unique version of num .

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