Representative Ways to Use Tuples
In this lesson, we'll explore the key usage of tuples, specifically unpacking
and converting tuples to lists.
Assigning Tuple Values to Multiple Variables at Once
Unpacking
refers to the method of assigning multiple values within a tuple to individual variables.
For example, given a tuple (1, 2, 3)
, you can split its values into three variables a
, b
, and c
all at once as shown below.
# Creating a tuple
my_tuple = (1, 2, 3)
# Unpacking
a, b, c = my_tuple
print(a) # Outputs 1
print(b) # Outputs 2
print(c) # Outputs 3
By utilizing unpacking, you can avoid the hassle of assigning each value individually, as shown below.
# Creating a tuple
my_tuple = (1, 2, 3)
# Assigning individually
a = my_tuple[0]
b = my_tuple[1]
c = my_tuple[2]
Unpacking is especially useful when a function returns multiple values.
Converting Between Lists and Tuples as Needed
There are times when you may want to convert a tuple to a list to modify its values or convert a list to a tuple to fix its values.
In such cases, Python allows easy conversion using the list()
and tuple()
functions.
Converting a Tuple to a List
To convert a tuple to a list, use the list()
function.
my_tuple = (1, 2, 3)
my_list = list(my_tuple)
print(my_list) # Outputs [1, 2, 3]
Once converted, the list can be freely modified by adding or updating its values.
Converting a List to a Tuple
Conversely, to convert a list to a tuple, use the tuple()
function.
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple) # Outputs (1, 2, 3)
When converted to a tuple, the values are fixed, allowing you to use them safely without worrying about modifications.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.