Reputation: 341
Let's say I have:
a=[1,2,3]
b=[4,5,6]
Now I want to create a list of list from a and b, I would do it like this:
c=[a,b]=[[1,2,3],[4,5,6]]
As a.append(b)
would result in: [1,2,3,b]=[1,2,3,[4,5,6]]
Now let's say there exists anew list which I want to append to c:
d=[7,8,9]
I now have to do c.append(d)
to get [[1,2,3],[4,5,6],[7,8,9]]
Because
e=[c,d]=[[[1,2,3],[4,5,6]],[7,8,9]]
How can I get a list of list from individual lists without know how my lists are structured?
Upvotes: 4
Views: 1499
Reputation: 21619
The two actions you are describing are distinctly different. The first is creating the outer list (a.k.a. c
) and the second is appending to it.
To make the process more uniform you can just start off with an outer list and append all the child lists to it.
c = []
a=[1,2,3]
b=[4,5,6]
d=[7,8,9]
c.append(a)
c.append(b)
c.append(d)
c is now
[[[1,2,3],[4,5,6]],[7,8,9]]
Upvotes: 1
Reputation: 892
A bit roundabout of a way but looks nice, using numpy
a = np.array([[1,2,3]])
b = np.array([[4,5,6]])
c = np.append(a,b,axis=0)
print(c.tolist())
gives you
[[1,2,3],[4,5,6]]
Appending another list in the same way keeps the structure of list of lists, for example
d = np.array([[7,8,9]])
e = np.append(c,d,axis=0)
print(e.tolist())
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Now this is quite roundabout. I would just keep everything in numpy arrays if possible.
EDIT: Figured out how to do this without numpy
Simply state each list as a list of lists to begin with
a = [[1,2,3]]
b = [[4,5,6]]
a.extend(b)
print(a)
[[1,2,3],[4,5,6]]
Furthermore you can do this
d = [[7,8,9]]
a.extend(d)
print(a)
[[1, 2, 3], [4, 5, 6], [4, 5, 6]]
Upvotes: 1
Reputation: 2227
Try this:
a = [1,2,3]
b = [4,5,6]
c = []
c.append(a)
c.append(b)
This should work, and only takes 2 simple lines.
Upvotes: 2