In Python, you can split tuples into multiple variables with tuple unpacking. You can unpack tuples with variable names separated by commas.

x, y, z = (0, 1, 2)

print(x)
print(y)
print(z)

#Output:
0
1
2

In Python, tuples are a collection of objects which are ordered and mutable. When working with tuples, it can be useful to be able to unpack the values of the tuples and create new variables.

You can unpack tuples with variable names separated by commas.

To split a tuple, just list the variable names separated by commas on the left-hand side of an equals sign, and then a tuple on the right-hand side.

Below is an example of splitting a tuple into three variables in Python.

x, y, z = (0, 1, 2)

print(x)
print(y)
print(z)

#Output:
0
1
2

Using Tuple Unpacking to Swap Values in Python

One application of splitting a tuple is when you want to efficiently swap the value of two variables in Python. We can swap values with tuple unpacking in the following way.

x = 2
y = 3

x, y = y, x     #equivalent to x, y = (y, x)

print(x)
print(y)

#Output:
3
2

Splitting a List of Tuples into Lists in Python

When working with lists of tuples, sometimes it can be useful to able to split the list of tuples into lists containing the values of each tuple element.

We can use tuple unpacking to create new lists from lists of tuples in a similar way as we can create variables from tuples.

Below is an example of how to split a list of tuples into lists using Python.

list_of_tuples = [(0,1),(1,2),(2,3),(3,4)]

def splitListOfTuples(lst):
    lst1 = []
    lst2 = []
    for x, y in lst:
        lst1.append(x)
        lst2.append(y)
    return (lst1, lst2)

x, y = splitListOfTuples(list_of_tuples)

print(x)
print(y)

#Output:
[0, 1, 2, 3]
[1, 2, 3, 4]

Hopefully this article has been useful for you to understand how to split a tuple into multiple variables using Python.

Categorized in:

Python,

Last Update: February 26, 2024