Karnivaurus
Karnivaurus

Reputation: 24131

Appending 2D lists

I want to create a 2-dimensional list F, by repeatedly appending other 2-dimensional lists to F. For example, suppose that I have the following lists x and y:

x = [[1, 2, 3], [4, 5, 6]]
y = [[7, 8, 9], [10, 11, 12]]

Then I want to append x to an empty matrix, and then append y to that matrix, for form F:

>>> F
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

However, if I try the following:

F = [[]]
F.append(x)
F.append(y)

Then I get the output:

>>> F
[[], [[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]

Which is not what I want. What is the correct way to go about this?

Upvotes: 0

Views: 57

Answers (3)

Padraic Cunningham
Padraic Cunningham

Reputation: 180481

Unless you want changes in x or y to effect F or vice versa you should make a deepcopy:

from copy import deepcopy

F = [deepcopy(x),deepcopy(y)]

Upvotes: 2

Bill Letson
Bill Letson

Reputation: 571

It looks like you want to append the elements of x and y to F, rather than x and y themselves. Use:

F = x + y

Or

F = []
F += x
F += y

Upvotes: 1

grc
grc

Reputation: 23575

Use list.extend:

>>> F = []
>>> F.extend(x)
>>> F.extend(y)
>>> F
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

Upvotes: 4

Related Questions