Learn Before
Tuple Operations
Beyond accessing items, additional operations can be performed on a tuple. Important operations include:
- Updating a tuple: Tuples are immutable, meaning their values cannot be changed after creation. However, if you do wish to change a tuple value, you can work around this by turning the tuple into a list (which is mutable), modifying the list, and then turning it back into a tuple.
tuple = ("apple", "orange", "banana") list = list(tuple) list[1] = "pineapple" tuple = tuple(list)
- Unpacking a tuple: When you create a tuple and feed it values, this is called packing. If you want to extract a tuple's values into variables, then this is called unpacking the tuple. You can unpack a tuple as shown.
tuple = ("apple", "orange", "banana") (red, orange, yellow) = tuple print(red) print(orange) print(yellow)
The number of variables must match the number of items in the tuple, unless using an asterisk to collect the items in a list. In the above example, red is assigned to apple, orange to orange, and yellow to banana. Collecting items within a list using an asterisk is shown below.
tuple = ("apple", "strawberry", "cherry", "orange", "banana") (red*, orange, yellow) = tuple print(red) print(orange) print(yellow)
Items in the tuple are added to red until the number of remaining variables (which is two, since orange and yellow come after red) matches the number of remaining items in the tuple. Thus, orange is assigned to orange and banana is assigned to yellow.
0
1
Tags
Python Programming Language
Data Science
Related
Tuple Operations
Tuple Reference
A programmer writes the following code snippet to update a collection of user roles. What will be the result when this code is executed?
user_roles = ('viewer', 'commenter', 'editor', 'admin') user_roles[1] = 'contributor' print(user_roles)Choosing the Right Data Structure for Constants
Choosing an Appropriate Data Structure