Multiple Assignment Syntax in Python

The multiple assignment syntax, often referred to as tuple unpacking or extended unpacking, is a powerful feature in Python. There are several ways to assign multiple values to variables at once.

Let's start with a first example that uses extended unpacking. This syntax is used to assign values from an iterable (in this case, a string) to multiple variables:

a, *b, c = 'Devlabs'

a: This variable will be assigned the first element of the iterable, which is 'D' in the case of the string 'Devlabs'.

*b: The asterisk (*) before b is used to collect the remaining elements of the iterable (the middle characters in the string 'Devlabs') into a list: ['e', 'v', 'l', 'a', 'b']

c: This variable will be assigned the last element of the iterable: 's'.

The multiple assignment syntax can also be used for numerous other tasks:

Swapping Values

a, b = b, a

This swaps the values of variables a and b without needing a temporary variable.

Splitting a List

first, *rest = [1, 2, 3, 4, 5]

first will be 1, and rest will be a list containing [2, 3, 4, 5].

Assigning Multiple Values from a Function

def get_values():
    return 1, 2, 3
x, y, z = get_values()

This assigns the values returned by get_values() to x, y, and z.

Ignoring Values

_, important_value = (42, "Hello")

Here, you're ignoring the first value with an underscore _ and assigning "Hello" to the important_value. In Python, the underscore is commonly used as a convention to indicate that a variable is being intentionally ignored or is a placeholder for a value that you don't intend to use.

Unpacking Nested Structures

data = ("Alice", (28, "New York"))
name, (age, city) = data

This unpacks a nested structure (Tuple in this example) into separate variables. We can use similar syntax also for Dictionaries:

data = {
    'person': {
        'name': 'Devlabs.ninja',
        'address': {
            'city': 'New York',
            'zipcode': '10001'
        }
    }
}

# Unpacking values from nested dictionaries using multiple assignment
person_info = data['person']
person_name, person_address = person_info['name'], person_info['address']
person_city, person_zipcode = person_address['city'], person_address['zipcode']

print(person_name)      # Output: 'Devlabs.ninja'
print(person_city)      # Output: 'New York'
print(person_zipcode)   # Output: '10001'

In this case, we first extract the 'person' dictionary from data, and then we use multiple assignment to further extract values from the nested dictionaries, making the code more concise.

Extended Unpacking with Slicing

first, *middle, last = [1, 2, 3, 4, 5]

first will be 1, middle will be a list containing [2, 3, 4], and last will be 5.

Split a String into a List

*split, = 'Devlabs.ninja'
print(split)
# ['D', 'e', 'v', 'l', 'a', 'b', 's', '.', 'n', 'i', 'n', 'j', 'a']

*split, is used for iterable unpacking. The asterisk (*) collects the remaining elements into a list variable named split. In this case, it collects all the characters from the string.

The comma , after *split is used to indicate that it's a single-element tuple assignment. It's a syntax requirement to ensure that split becomes a list containing the characters.