51

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]]

Yur3k
  • 669
  • 1
  • 6
  • 9
  • 3
    `l1 + l2`. You can simply add them. – Willem Van Onsem Oct 21 '17 at 17:36
  • 1
    Python makes this ridiculously easy: `[1, 2, 3] + [4, 5, 6]` that's it. – Christian Dean Oct 21 '17 at 17:39
  • They look like plain Python lists, not [arrays](https://docs.python.org/3/library/array.html). – PM 2Ring Oct 21 '17 at 17:39
  • 1
    @PM2Ring That's probably what he meant. I've seen quite a few people who don't understand the difference between list and arrays in Python. They use the two terms synonymously. – Christian Dean Oct 21 '17 at 17:41
  • 3
    @ChristianDean Indeed, and I'm doing my small part to reverse that trend. ;) It may seem a little pedantic, but when there are two built-in array-like types (lists and tuples), the arrays of the `array` module I linked above, plus Numpy arrays, I think it's important to give these things their correct names. – PM 2Ring Oct 21 '17 at 17:41
  • See https://docs.python.org/3/tutorial/introduction.html#lists Tutorial about list –  Oct 21 '17 at 17:49

2 Answers2

80

+ 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]
Sreeram TP
  • 11,346
  • 7
  • 54
  • 108
8

By using the + operator, like this:

>>> [1, 2] + [3, 4]
[1, 2, 3, 4]
gsamaras
  • 71,951
  • 46
  • 188
  • 305