JavaScript has a spread operator( ... ) which is used to expand elements from an iterable into  individual elements.  This allows you to easily work with the the elements of the iterable in contexts like function calls, array literals, object literals, e.t.c.

While Python does not have a spread operator per se, we can achieve similar functionality using the unpacking operators (* for iterables like lists and tuples, and ** for dictionaries)

In this article, we will explore various aspects of the spread operator in Python, including its syntax, use cases, limitations, and how it compares to the spread operator in other languages.

Unpacking operators

Python provides two primary unpacking operators:

  • single-asterisk(*) : for unpacking iterables e.g list, tuples, e.t.c
  • double-asterisk(**): for unpacking mappings e.g dictionaries

The single-asterisk(*) operator

We use the single asterisk operator to unpack an iterable object. We can effectively use it to spread the individual elements where they are required.

Spread in function calls

ExampleEdit & Run
def add(a, b, c):
    return a + b + c

numbers = [10, 20, 30]
result = add(*numbers)  # Equivalent to add(10, 20, 30)
print(result)  # Output: 60
Output:
60 [Finished in 0.01781633299992791s]

In the above example, the *numbers syntax unpacks the list [10, 20, 30] into individual arguments for the add() function.

Combining lists and other iterables

ExampleEdit & Run
list1 = [1, 2, 3]
list2 = [4, 5, 6]

result = [*list1, *list2]
print(result)
Output:
[1, 2, 3, 4, 5, 6] [Finished in 0.021831935000136582s]

In the above example, the individual elements of the two lists i.e list1 and list2 are spread into a single list i.e result

Destructuring Assignments

ExampleEdit & Run
a, *b, c = [1, 2, 3, 4, 5]
print(a)  # Output: 1
print(b)  # Output: [2, 3, 4]
print(c)  # Output: 5
Output:
1 [2, 3, 4] 5 [Finished in 0.0347329640001135s]

In the above example, the *b captures all intermediate elements between a and c .

Double-asterisk(**) operator

We can use the double-asterisk(**) operator to spread dictionaries and other mappings. This way we can retrieve individual key-value pairs from the mapping.  This is particularly useful when working with functions that accept keyword arguments or for merging dictionaries.

ExampleEdit & Run
def greet(name, age):
    print(f"Hello {name}, you are {age} years old")

details = {'name': 'John', 'age': 23}

greet(**details)
Output:

The **details unpacks the dictionary into keyword arguments for the greet() function. 

Merging dictionaries

We can merge multiple dictionaries into a single dictionary using the double asterisk operator.

ExampleEdit & Run
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}

merged = {**dict1, **dict2}  # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
print(merged)
Output:
60 [Finished in 0.03304698300007658s]