Python offers numerous data types for storing and manipulating information. Lists, tuples, sets, and dictionaries are among the most frequently used.
Lists, however, are simple ordered collections of elements, allowing for flexible additions and deletions as needed. They are particularly useful for dynamically tracking multiple elements.
In this guide, we’ll explore how to merge lists in Python 3.11, providing examples to demonstrate their functionality.
If you're new to Python, here’s how to run examples from this tutorial to practice list merging:
main.py
.cd C:\Users\
Execute the following command to run your script:
python main.py
Or:
python3 main.py
The result of the program execution will be displayed in the console.
The +
operator can be used to merge two lists in Python. It appends one list to the end of another, resulting in a new list.
a1 = [1, 12, 5, 49, 56]
a2 = [27, 36, 42]
list= a1 + a2
print(list)
Output:
[1, 12, 5, 49, 56, 27, 36, 42]
Let’s look at another example, where a Python program generates three lists with random numbers and combines them into a single list:
import random
def generate_and_combine_lists(length):
if length <= 0:
raise ValueError("List length must be a positive number")
list1 = [random.randint(1, 10) for _ in range(length)]
list2 = [random.randint(1, 100) for _ in range(length)]
list3 = [random.randint(1, 1000) for _ in range(length)]
try:
combined_list = list1 + list2 + list3
return list1, list2, list3, combined_list
except TypeError as e:
print(f"Error combining lists: {e}")
return None
list_length = 5
list1, list2, list3, combined_list = generate_and_combine_lists(list_length)
if combined_list:
print(f"List 1: {list1}")
print(f"List 2: {list2}")
print(f"List 3: {list3}")
print(f"Combined List: {combined_list}")
Output:
List 1: [4, 7, 3, 2, 10]
List 2: [43, 73, 5, 61, 39]
List 3: [500, 315, 935, 980, 224]
Combined List: [4, 7, 3, 2, 10, 43, 73, 5, 61, 39, 500, 315, 935, 980, 224]
The *
operator can easily combine lists in Python by unpacking the elements of collections into indexed positions.
If you have two lists, for example:
list1 = [1, 12, 5, 49, 56]
list2 = [27, 36, 42]
Using the *
operator replaces the list with its individual elements at the specified index positions, effectively "unpacking" the list contents.
list1 = [1, 12, 5, 49, 56]
list2 = [27, 36, 42]
combined_list = [*list1, *list2]
print(str(combined_list))
Output:
[1, 12, 5, 49, 56, 27, 36, 42]
Below is another example where randomly generated Python lists are combined using the *
operator:
import random
def generate_and_combine_lists(length):
if length <= 0:
raise ValueError("List length must be a positive number")
list1 = [random.randint(1, 100) for _ in range(length)]
list2 = [random.randint(1, 100) for _ in range(length)]
list3 = [random.randint(1, 100) for _ in range(length)]
return list1, list2, list3, *list1, *list2, *list3
list_length = 5
list1, list2, list3, *combined_list = generate_and_combine_lists(list_length)
print(f"List 1: {list1}")
print(f"List 2: {list2}")
print(f"List 3: {list3}")
print(f"Combined List: {combined_list}")
Output:
List 1: [10, 43, 17, 74, 99]
List 2: [65, 91, 56, 37, 37]
List 3: [33, 39, 87, 27, 82]
Combined List: [10, 43, 17, 74, 99, 65, 91, 56, 37, 37, 33, 39, 87, 27, 82]
The *
operator efficiently merges the contents of list1
, list2
, and list3
into a single combined_list
.
In this method, we use a for
loop to iterate over the second list. Each element from the second list is added to the first list using the append()
method. The result is a new list that combines the elements of both lists.
list1 = [6, 11, 32, 71, 3]
list2 = [18, 54, 42]
print("Original List 1:", str(list1))
for x in list2:
list1.append(x)
print("Combined List:", str(list1))
Output:
Original List 1: [6, 11, 32, 71, 3]
Combined List: [6, 11, 32, 71, 3, 18, 54, 42]
We can also use list comprehensions in Python to combine lists efficiently. A list comprehension is a concise way to generate a new list based on an iterable.
list1 = [5, 73, 232, 1, 8, 19]
list2 = [84, 56, 7, 10, 20, 30]
combined_list = [j for i in [list1, list2] for j in i]
print("Combined List:", str(combined_list))
Output:
[5, 73, 232, 1, 8, 19, 84, 56, 7, 10, 20, 30]
The extend()
method in Python iterates over the elements of the provided list and appends them to the current list, effectively merging both lists.
import random
list1 = [random.randint(10, 20) for _ in range(5)]
list2 = [random.randint(20, 50) for _ in range(3)]
print("First List:", str(list1))
list1.extend(list2)
print("Combined List:", str(list1))
Output:
First List: [19, 19, 16, 17, 16]
Combined List: [19, 19, 16, 17, 16, 47, 21, 31]
In this approach, all elements from list2
are added to list1
, updating list1
directly with the combined contents.
The itertools
module in Python provides various functions for working with iterators, which can be used to efficiently generate lists. It is particularly useful for generating large lists created with complex rules, as it avoids creating the entire list in memory at once, which can lead to memory overflow for very large datasets.
We can also use the itertools.chain()
function from the itertools
module to combine lists in Python.
import itertools
list_of_lists = [[1, 5], [3, 4], [7, 12]]
chained_list = list(itertools.chain(*list_of_lists))
print(chained_list)
Output:
[1, 5, 3, 4, 7, 12]
Let's consider a case where we generate letters and combine them into a list.
import itertools
import string
def generate_letter_range(start, stop):
for letter in string.ascii_lowercase[start:stop]:
yield letter
list1 = generate_letter_range(0, 3)
list2 = generate_letter_range(7, 16)
combined_list = list(itertools.chain(list1, list2))
print(combined_list)
Output:
['a', 'b', 'c', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p']
We can also combine lists of numbers using itertools.chain()
.
import itertools
list1 = [5, 73, 232, 1, 8]
list2 = [19, 84, 56, 7]
list3 = [10, 20, 30]
combined_list = list(itertools.chain(list1, list2, list3))
print(combined_list)
Output:
[5, 73, 232, 1, 8, 19, 84, 56, 7, 10, 20, 30]
Let's generate random letters in two lists, with one list containing 3 letters and the other containing 7, and then combine them.
import itertools
import random
import string
def generate_letter_list(num_letters):
for i in range(num_letters):
yield random.choice(string.ascii_letters)
num_list1 = 3
num_list2 = 7
list1 = generate_letter_list(num_list1)
list2 = generate_letter_list(num_list2)
combined_list = list(itertools.chain(list1, list2))
print(combined_list)
Output:
['d', 'e', 'O', 'M', 'q', 'i', 'N', 'V', 'd', 'C']
Each of these methods for merging lists in Python has its own particularities, and the choice of which one to use depends on what you need to accomplish, the amount of data you have, and how quickly you want to get the result. Understanding these methods will help you to work more efficiently with data in your Python projects. Choose the method that suits your needs, and don't hesitate to try different approaches to get the best result!