Learn Before
Relation

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

Updated 2021-05-17

Tags

Python Programming Language

Data Science