How To Assign Multiple Values To A Variable In Python

When working with Python, there are times when you may need to assign multiple values to a variable within the same program.

In this tutorial, we will learn how to assign multiple values to a single variable in Python using different techniques. Assigning multiple values to a variable is also known as tuple packing and sequence unpacking.

Step 1: Assigning multiple values using tuple packing

Python provides a convenient way to assign multiple values to a variable by packing values into a tuple. A tuple is an immutable sequence type in Python that stores a collection of objects. Here’s an example of assigning multiple values to a single variable using tuple packing:

In the example above, we created a tuple named coordinates and packed it with two float values, representing latitude and longitude. Now, let’s understand how to access the values in the tuple.

Latitude: 52.2297
Longitude: 21.0122

Step 2: Assigning multiple values using sequence unpacking

Besides tuple packing, we can also use sequence unpacking to assign multiple values to a variable. Sequence unpacking is a technique where we unpack the values from a sequence (like a list or a tuple) and assign them to variables.

Here’s an example of assigning multiple values to a variable using sequence unpacking:

Value of x: 1
Value of y: 2
Value of z: 3

In the example above, we have a list with three integer values. We unpacked the list and assigned the values to three separate variables x, y, and z.

It’s important to note that the number of variables on the left side of the assignment must match the number of elements in the sequence. If the number of variables and elements do not match, Python will raise a ValueError.

Step 3: Assigning multiple values using the * operator

Python allows you to use the * operator to assign multiple values to a single variable when working with sequences. The * operator can be used for extended unpacking and is available in Python 3.0 and higher.

Here’s an example of using the * operator to assign multiple values to a single variable:

Value of a: 1
Value of b: [2, 3, 4]
Value of c: 5

In the example above, we used the * operator to assign multiple values from a list to a single variable, b. The variable a is assigned the first element of the list, c is assigned the last element, and b contains the remaining elements in a new list.

Full code

Latitude: 52.2297
Longitude: 21.0122

Value of x: 1
Value of y: 2
Value of z: 3

Value of a: 1
Value of b: [2, 3, 4]
Value of c: 5

Conclusion

In this tutorial, we learned how to assign multiple values to a single variable in Python using different techniques, including tuple packing, sequence unpacking, and using the * operator for extended unpacking. These techniques can be helpful when working with large data sets or writing more efficient code.