0

I know there are a lot of questions like this one, but I haven't found my answer so far.

I am trying to dynamically fill a list with other lists, but I don't know why my code doesn't do what I want.

My code:

x = [1,2,3]
y = [4,5,6]

x.append(y)
print (x)

What I get:

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

What I realy want:

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

My goal would be, to dynamically add more dimensions arranged like this.

Can somebody tell me, what I'm doing wrong?

Thanks a lot.

Tike Myson
  • 27
  • 5
  • 1
    You want `x = [x, y]`. After that you have a list of lists and you can `.append` to it. – Samwise May 18 '20 at 14:20
  • Start with an empty list and append both `x` and `y`... etc – trincot May 18 '20 at 14:20
  • 1
    Does this answer your question? [Converting a 1D list into a 2D list with a given row length in python](https://stackoverflow.com/questions/27371064/converting-a-1d-list-into-a-2d-list-with-a-given-row-length-in-python) – Harshit May 18 '20 at 14:20

3 Answers3

0

What you want is create a list of lists. You can do:

x = [1,2,3]
y = [4,5,6]
l = [x,y]
print(l)

Actually, if you want to deal with multi-dimensional arrays, you should probably look at the numpy library (https://numpy.org/)

GabrielC
  • 322
  • 1
  • 6
0

In your example, x is a list containing three elements (integers). With append, you add a new element. By appending y, you are adding a list as a fourth element (3 integers, one list).

If you want to create a list of lists, tread x and y as elements for that, and combine them in a list:

x = [1,2,3]
y = [4,5,6]
list_of_lists = [x,y]

list_of_lists will then be [[1, 2, 3], [4, 5, 6]].

You can add another list by appending them:

list_of_lists.append([7,8,9])

... which will result in list_of_lists being [[1, 2, 3], [4, 5, 6], [7, 8, 9]].

cjac
  • 113
  • 1
  • 9
  • Perfect thank you. Does the .append() function also work like this if the list_of_lists is empty at the beginning? – Tike Myson May 18 '20 at 14:44
  • Yes. The "append-function" is more likely an object-method, provided by a list-instance. So instead of lists_of_lists = [x,y] you can start with an empty list, and call its append-method afterwards to add the elements x and y (being lists itself). – cjac May 18 '20 at 15:01
0
x = [1,2,3]
y=[22,33,9]
x=(x,y)
print (list(x))
>> [[1, 2, 3], [22, 33, 9]]
x=list(x) #Perform type conversion of the output 'x' to get in list type
x.append([13,32,12])#then append the data you want
print (x)
>> [[1, 2, 3], [22, 33, 9], [13, 32, 12]]
Sanyal
  • 864
  • 10
  • 22