Home > OS >  How to add a list to another list as a list
How to add a list to another list as a list

Time:07-28

I have multiple lists like below

x = []
a = [1, 2, 3]
b = [4, 5, 5]

I am trying to append a and b to x and get a result like below

print(x)
#[[1, 2, 3], [4, 5, 6]]

But I have no idea how to do this task. Append or other things just makes it like [1, 2, 3, 4, 5, 6] which i don't want to. Is there any methods in python for that or should I use some other packages?

CodePudding user response:

I just found out there is a method called insert for that... Sorry i am a newbie. Problem solved

CodePudding user response:

You can use append method try this:

l = []
a = [1, 2, 3]
b = [4, 5, 5]

l.append(a)
print(l)
l.append(b)
print(l)

Output:

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

CodePudding user response:

You can simply use append to insert any object in list including list. list is an object so you can simply do that an it'll work

>>> x = []
>>> a = [1, 2, 3]
>>> b = [4, 5, 5]
>>> x.append(a)
>>> x
[[1, 2, 3]]
>>> x.append(b)
>>> x
[[1, 2, 3], [4, 5, 5]]

  • Related