Python Docs
Python Tuples — Full Notes
A tuple is an ordered, unchangeable collection in Python. Tuples are used to store multiple items in a single variable and are written using round brackets ( ).
What is a Tuple?
Example of creating a tuple:
mytuple = ("apple", "banana", "cherry")Printing a Tuple
thistuple = ("apple", "banana", "cherry")
print(thistuple)Tuples Allow Duplicate Values
Since tuples are indexed, duplicate values are allowed.
thistuple = ("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)Tuple Length
Use len() to get the number of elements in a tuple.
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))Tuple With One Item
A tuple with one item must include a comma, otherwise Python treats it as a string.
thistuple = ("apple",)
print(type(thistuple))thistuple = ("apple")
print(type(thistuple))Data Types in Tuples
Tuples can contain any data type, including mixed types.
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)tuple1 = ("abc", 34, True, 40, "male")Tuple Type
Tuples belong to the tuple data type.
mytuple = ("apple", "banana", "cherry")
print(type(mytuple))tuple() Constructor
You can also create a tuple using the tuple() constructor.
thistuple = tuple(("apple", "banana", "cherry"))
print(thistuple)Access Tuple Items
Tuple items can be accessed using indexes or slicing.
Access by Index
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])Negative Indexing
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])Range of Indexes
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])Updating Tuples
Tuples are immutable, meaning their values cannot be changed directly. However, you can convert a tuple into a list, modify it, and convert it back.
Change Tuple Values (Workaround)
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)Add Items (via list conversion)
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.append("orange")
thistuple = tuple(y)Add Tuple to Tuple
thistuple = ("apple", "banana", "cherry")
y = ("orange",)
thistuple += y
print(thistuple)Tuple Packing & Unpacking
Packing
fruits = ("apple", "banana", "cherry")Unpacking
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruitsUsing Asterisk (*)
Asterisk collects remaining values into a list while unpacking.
fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
(green, yellow, *red) = fruitsfruits = ("apple", "mango", "papaya", "pineapple", "cherry")
(green, *tropic, red) = fruitsTuple Methods
Tuples have only two built-in methods:
| Method | Definition |
|---|---|
| count() | Returns the number of times a value occurs in a tuple. |
| index() | Returns the index of the first occurrence of a value. |