Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I merge lists in python? [duplicate]

Tags:

python

arrays

I have 2 lists, for example: [1, 2, 3] and [4, 5, 6] How do I merge them into 1 new list?: [1, 2, 3, 4, 5, 6] not [[1, 2, 3], [4, 5, 6]]

like image 743
Yur3k Avatar asked Oct 21 '17 17:10

Yur3k


People also ask

How do you merge duplicates in python list?

Python merges two lists without duplicates could be accomplished by using a set. And use the + operator to merge it.

How do you merge elements in a list python?

One simple and popular way to merge(join) two lists in Python is using the in-built append() method of python. The append() method in python adds a single item to the existing list. It doesn't return a new list of items, instead, it modifies the original list by adding the item to the end of the list.


2 Answers

+ operator can be used to merge two lists.

data1 = [1, 2, 3]
data2 = [4, 5, 6]

data = data1 + data2

print(data)

# output : [1, 2, 3, 4, 5, 6]

Lists can be merged like this in python.

Building on the same idea, if you want to join multiple lists or a list of lists to a single list, you can still use "+" but inside a reduce method like this,

from functools import reduce 

l1 = [1, 2, 3]
l2 = [4, 5, 6]
l3 = [7, 8, 9]
l4 = [10, 11, 12]

l = [l1, l2, l3, l4]

data = reduce(lambda a, b: a+b, l)
print(data)

# output : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
like image 110
Sreeram TP Avatar answered Sep 26 '22 11:09

Sreeram TP


By using the + operator, like this:

>>> [1, 2] + [3, 4]
[1, 2, 3, 4]
like image 31
gsamaras Avatar answered Sep 25 '22 11:09

gsamaras