In This Article
In this article, we will delve into Python spread operator sometimes also known as unpacking operator, and use various examples to show its usage.
The “spread operator” is not a native feature in Python like it is in JavaScript. However, you can achieve similar functionality in Python using the unpacking operator, *
, on iterables.
In Python, spreading is a mechanism that allows you to extract elements from lists, tuples, and dictionaries and assign them to multiple variables simultaneously or combine them into other iterables.
Understanding the Basics of Spreading or Unpacking
The unpacking operator or Python spread operator (*
), when applied to an iterable, extracts the elements in the iterable so that those elements can be used in various contexts.
The code below shows the fundamental usage of the spread operator in Python:
numbers = (1, 2, 3, 4, 5)
# Spread tuple into list
lst = [*numbers]
print(lst) # Output: [1, 2, 3, 4, 5]
print(type(lst)) # Output: <class 'list'>
In this example, a tuple named numbers
is unpacked/spred into a list named lst
using the spread operator. lst
holds the same elements as the original tuple numbers
.
The print
function calls confirm the successful creation of the list, displaying the content of lst
as [1, 2, 3, 4, 5]
, and verifying its type as <class 'list'>
.
This is just a simple usage case; the next examples will showcase more applications of spreading data.
Python Spread Operator Uses and Examples
Having seen a basic example of the Python spread operator or unpack operator (*
), we will explore more examples that delve into different use cases of this operator.
These forthcoming examples will show how versatile the Python spread operator is in handling various data structures and situations.
Copying lists using Python Spread Operator
Unpacking is a concise way to copy the elements of a list into a new list.
This is particularly useful when you want to create an independent copy of an existing list.
original_list = [1, 2, 3, 4, 5]
# Copying a list using unpacking
copied_list = [*original_list]
print(copied_list) # Output: [1, 2, 3, 4, 5]
We can also make use of a similar technique to flatten a list containing some nested lists.
We will define a function, flatten
that takes a nested list as input and returns a flattened list, containing no sublists.
We assume that there is only one level of nesting.
def flatten(lst):
newlist = [] # Initialize an empty list to store the flattened elements.
# Iterate through each element in the input list.
for e in lst:
# Check if the element is a list (sublist).
if isinstance(e, list):
# Use unpacking to combine elements of the sublist into the new list.
newlist = [*newlist, *e]
else:
# If the element is not a list, add it directly to the new list.
newlist = [*newlist, e]
return newlist # Return the flattened list.
# Test cases with nested lists.
list_1 = [1, [2, 5, 6], 2, 8, 9, [9, 2, 3, 5], 8]
list_2 = [5, [2, 8], 4, [3, 6, 9], 8, 7]
list_3 = [[8, 2], [3, 7, 3], 5, [1, 9, 8, 9], 2, 5, 5]
# Print the results of the flatten function for each test case.
print(f"{flatten(list_1) = }") # Output: flatten(list_1) = [1, 2, 5, 6, 2, 8, 9, 9, 2, 3, 5, 8]
print(f"{flatten(list_2) = }") # Output: flatten(list_2) = [5, 2, 8, 4, 3, 6, 9, 8, 7]
print(f"{flatten(list_3) = }") # Output: flatten(list_3) = [8, 2, 3, 7, 3, 5, 1, 9, 8, 9, 2, 5, 5]
The function iterates through each element of the input list, checking if the element is itself a list.
Then it makes use of unpacking as needed, depending on whether the current element is a sublist or not.
See the output below for the result of running three test cases on the function:
Merging lists using the Python Spread Operator
With unpacking or spreading, you can merge two or more lists into a single list.
Here’s an example of merging two lists named list1
and list2
:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
# Merging lists using unpacking
merged_list = [*list1, *list2]
print(merged_list) # Output: [1, 2, 3, 4, 5, 6]
The code that carries out the merging is [*list1, *list2]
.
This results in individual elements from each list spread out and combined into a new list named merged_list
. The output we get shows the successful merging of list1
and list2
:
We can follow the same scheme when unpacking tuples.
The code to do this is not much different from the one shown previously.
For example, in order to merge three tuples (t1
, t2
and t3
) into a single tuple, we can make use of the following code snippet:
t1 = (13, 56, 5, 98)
t2 = (23, 18)
t3 = (12, 10, 5)
# Merging tuples using unpacking
merged_tuple = (*t1, *t2, *t3)
print(merged_tuple) # Output: (13, 56, 5, 98, 23, 18, 12, 10, 5)
The resulting tuple, merged_tuple
, contains all the individual elements from the original tuples in a single sequence.
In this specific example, the print(merged_tuple)
statement produces the following output:
Note
Learn more about Python lists from this tutorial: List in Python.
Unpacking an Iterable into a Function Argument
We’ve seen several interesting uses of unpacking, or Python’s spread operator: copying a list into another, and merging lists together (or merging tuples together).
In this next example, we will show how to unpack, or spread, an iterable into function arguments:
def add_numbers(a, b, c):
return a + b + c
numbers = [1, 2, 3]
# Unpacking a list into function arguments
result = add_numbers(*numbers)
print(result) # Output: 6
We had to make sure that the number of elements in the numbers
list was the same as the number of expected arguments in the add_numbers
function. If not, we will get a TypeError
.
Using Spread Operator to Unpacking a Dictionary
In Python, you can use the spread operator (`**`) to unpack the contents of a dictionary into another dictionary.
This feature comes in handy when you want to merge dictionaries or pass multiple keyword arguments to a function efficiently.
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}
To unpack the person dictionary, you can use the Python spread operator as follows:
unpacked_person = {**person}
Now, unpacked_person
will contain the same key-value pairs as a person. This technique is particularly useful when you want to create a copy of a dictionary or merge multiple dictionaries into one.
Here’s an example of merging two dictionaries using the Python spread operator:
person_details = {'gender': 'Female', 'occupation': 'Engineer'}
merged_person = {**person, **person_details}
In this example, merged_person
will contain the combined key-value pairs from both person and person_details
.
Keep in mind that if there are overlapping keys between dictionaries, the values from the rightmost dictionary take precedence. This behavior is important to consider when merging dictionaries.
Using the spread operator to unpack dictionaries provides a concise and readable way to work with dictionary data in Python.
Using Spread Operator to Unpacking a Dictionary into Function Arguments
The spread operator (**
) in Python is not only useful for merging dictionaries but also for passing the key-value pairs of a dictionary as keyword arguments to a function.
This feature is handy when you have a dictionary of parameters that you want to use to call a function.
Now, let’s say we have a function that takes individual parameters:
def print_person_info(name, age, city):
print(f"Name: {name}, Age: {age}, City: {city}")
If we want to extract values from a dictionary and pass them as arguments, we can use the spread operator in Python to unpack the dictionary directly into the function:
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}
print_person_info(**person)
The above code is equivalent to:
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}
print_person_info(name=person['name'], age=person['age'], city=person['city'])
Using the Python spread operator in this way with dictionaries matches the key-value pairs in the person dictionary to the function parameters based on their keys.
This is useful when the functions called have a large number of parameters or when the parameters are subject to change.
It makes the code more readable and reduces the likelihood of errors when calling the function with the wrong order or missing arguments.
Conclusion
In conclusion, the Python unpacking operator,*
, is a powerful feature that empowers developers to handle iterable objects with a lot of flexibility.
Whether you are copying lists, merging iterables, or passing elements to functions, unpacking simplifies complex operations into concise and readable code.
That’s it for this tutorial. We have more Python coding tutorials. Please feel free to check them out. Also, you might want to hire a live Python tutor for learning programming.