The simplest way to merge two lists in Python is by using the +
operator:
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print(c)
# [1, 2, 3, 4, 5, 6]
Extending a list
If you don't want to create a new list you can extend an existing list with items from another list using the extend()
method or the +=
operator for shorthand:
a = [1, 2, 3]
b = [4, 5, 6]
a.extend(b)
print(a)
# [1, 2, 3, 4, 5, 6]
b += a
print(b)
# [4, 5, 6, 1, 2, 3, 4, 5, 6]
Removing duplicates
If you want to remove duplicates when merging lists you can do this by using a list comprehension.
a = [1, 2, 3, 4]
b = [4, 5, 6, 7]
c = a + [num for num in b if not num in a]
print(c)
# [1, 2, 3, 4, 5, 6, 7]
Or if you don't need to retain the order of items you can simply merge the lists and convert them to a set.
a = [1, 2, 3, 4]
b = [4, 5, 6, 7]
c = set(a + b)
print(c)
# {1, 2, 3, 4, 5, 6, 7}
Finally, if you just want to iterate over multiple lists (or other iterables) without creating a new list you can use itertools.chain()
to create a generator that will iterate over each item.import itertools
a = [1, 2]
b = [3, 4]
c = (5, 6)
d = {7, 8}
for item in itertools.chain(a, b, c, d):
print(item, end=" ")
# 1 2 3 4 5 6 8 7