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!
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.
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 .
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.
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.
Just ADD them!
new_matrix = matrix1 + matrix2
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With