Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Inserting a list of lists into another list of lists [duplicate]

Tags:

python

list

I would like to take the following lists:

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

matrix2 = [
[A, B, C, D],
[E, F, G, H]
]

and combine them into:

new_matrix = [
[A, B, C, D],
[E, F, G, H],
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]

And I can't seem to figure out a good method. Insert() puts the whole list in, resulting in a list of lists of lists. Any suggestions would be appreciated!

like image 715
user2238685 Avatar asked Apr 24 '13 20:04

user2238685


People also ask

How do you merge two lists without duplicates in Python?

How to remove duplicate elements while merging two lists. Python sets don't contain duplicate elements. To remove duplicate elements from lists we can convert the list to set using set() and then convert back to list using list() constructor. The fastest way to merge lists in python.

Can you append a list to another list Python?

Python provides a method called . append() that you can use to add items to the end of a given list. This method is widely used either to add a single item to the end of a list or to populate a list using a for loop. Learning how to use .

How do I make a nested list in Python?

Python Nested Lists First, we'll create a nested list by putting an empty list inside of another list. Then, we'll create another nested list by putting two non-empty lists inside a list, separated by a comma as we would with regular list elements.

How do you add duplicates to a list in Python?

Method #1 : Using * operator We can employ * operator to multiply the occurrence of the particular value and hence can be used to perform this task of adding value multiple times in just a single line and makes it readable.


2 Answers

Just ADD them!

new_matrix = matrix1 + matrix2
like image 163
nye17 Avatar answered Nov 14 '22 23:11

nye17


Use + to add them:

In [59]: new_matrix = matrix2 + matrix1

In [60]: new_matrix
Out[60]: 
[['A', 'B', 'C', 'D'],
 ['E', 'F', 'G', 'H'],
 [1, 2, 3, 4],
 [5, 6, 7, 8],
 [9, 10, 11, 12]]
like image 41
Ashwini Chaudhary Avatar answered Nov 14 '22 22:11

Ashwini Chaudhary