Expanding Sequence Elements with the Spread Operator
The Spread Operator
is commonly used to unpack or expand elements of data structures like lists, tuples, and dictionaries into other data structures.
The spread operator can be utilized in various situations such as passing arguments to functions, merging lists, or assigning values to variables.
You can unpack elements of a list or dictionary using the *
spread operator as shown below.
numbers = [1, 2, 3] print("numbers:", *numbers) # Output: 1 2 3
The unpacked elements are printed with a space between each element.
Using the Spread Operator with Lists
You can also use the spread operator to merge two lists as shown below.
a = [1, 2, 3] b = [4, 5, 6] combined = [*a, *b] print("combined:", combined) # Output: [1, 2, 3, 4, 5, 6]
Using the Spread Operator with Dictionaries
When using the *
spread operator with dictionaries, only the keys
are unpacked.
dict1 = {'a': 1, 'b': 2} print("dict1:", *dict1) # Output: a b
If you want to unpack both key-value pairs, you need to use **
to expand the dictionary.
dict1 = {'a': 1, 'b': 2} dict2 = {'c': 3, 'd': 4} combined = {**dict1, **dict2} print("combined:", combined) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
As demonstrated, the spread operator is primarily used for expanding or merging data types such as lists, tuples, and dictionaries.
Using the *
operator in a dictionary can unpack key-value pairs.
Guidelines
AI Tutor
Publish
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result