简体   繁体   中英

append list of lists in python

I am trying to append a list of lists with Python but there is an error. My problem is just with append function. I explain my problem better. I am using a loop. The first time the append function works fine. But for the second time, the function does not work.

When we do the first loop, we get the right result:

list1 = [1,2,3]
list2  = [4,5,6]
list3 = []
list3.append(list1)
list3.append(list2)
print(list3)

result:

[[1, 2, 3], [4, 5, 6]]

With the second loop, append does not work correctly. One extra bracket.

liste4 = []
liste4.append(list3)
liste4.append(list1)
print(liste4)

result:

[[[1, 2, 3], [4, 5, 6]], [1, 2, 3]]

But the result I want is this:

[[1, 2, 3], [4, 5, 6], [1, 2, 3]]

Define list3 as an empty list and append to it:

list1 = [1,2,3]
list2  = [4,5,6]
list3 = []
list3.append(list1)
list3.append(list2)
print(list3)

Output:

[[1, 2, 3], [4, 5, 6]]

you could just do list3 = [list1, list2]

If you want it in a function, here is a go aa List of List creator, which may take multiple lists as the input:

def LoL(*lists):
    out = [x for x in lists]
    return out

list1 = [1,2,3]
list2 = [4,5,6]
list3 = [7,8,9]

list4 = LoL(list1,list2,list3)
list4
>>> [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
list1 = [1,2,3]
list2  = [4,5,6]
list3 = []
list3.append(list1)
list3.append(list2)
print(list3)

result:

[[1, 2, 3], [4, 5, 6]]

With the second loop:

liste4 = list3
liste4.append(list1)
print(liste4)

result:

[[1, 2, 3], [4, 5, 6], [1, 2, 3]]

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