Tuples In Python
Python Tuples: Comprehensive Theory
Tuples are used to store multiple items in a single variable. A tuple is a collection which is ordered and unchangeable.
1. Characteristics of Tuples
- Ordered: Tuples have a defined order, and that order will not change.
- Unchangeable (Immutable): We cannot change, add, or remove items after the tuple has been created.
- Allow Duplicates: Since tuples are indexed, they can have items with the same value.
2. Creating a Tuple
Tuples are written with round brackets ().
mytuple = ("apple", "banana", "cherry")
Create Tuple With One Item
To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple.
thistuple = ("apple",)
print(type(thistuple)) # <class 'tuple'>
# NOT a tuple
thistuple = ("apple")
print(type(thistuple)) # <class 'str'>
3. Accessing Tuple Items
You can access tuple items by referring to the index number, inside square brackets [].
thistuple = ("apple", "banana", "cherry")
print(thistuple[1]) # Output: banana
Negative Indexing & Slicing
Tuples support negative indexing and slicing just like lists.
-1refers to the last item.[2:5]refers to items from index 2 to 4.
4. Updating Tuples (Workaround)
Since tuples are unchangeable (immutable), you cannot change them after creation. However, there is a workaround: you can convert the tuple into a list, change the list, and convert the list back into a tuple.
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x) # ("apple", "kiwi", "cherry")
5. Unpacking Tuples
When we create a tuple, we normally assign values to it. This is called "packing" a tuple. We can also extract the values back into variables. This is called "unpacking".
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green) # apple
print(yellow) # banana
print(red) # cherry
Using Asterisk *
If the number of variables is less than the number of values, you can add an * to the variable name and the values will be assigned to the variable as a list.
fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
(green, yellow, *red) = fruits
print(green) # apple
print(yellow) # banana
print(red) # ['cherry', 'strawberry', 'raspberry']
6. Tuple Methods
Python has two built-in methods that you can use on tuples:
| Method | Description |
| :--- | :--- |
| count() | Returns the number of times a specified value occurs in a tuple |
| index() | Searches the tuple for a specified value and returns the position of where it was found |