Python Tuple
In Python, a tuple is an ordered collections of items that cannot be changed after it is created. It is similar to a list, but unlike lists, tuples are immutable, meaning you cannot add, remove, or modify their elements.
Creating a Tuple
To create a tuple in Python, you put the items inside parentheses () and separate them with commas.
For example:
# Empty tuple
empty = ()
# Tuple of integers
numbers = (1, 2, 3, 4)
# Tuple of strings
person = ("james", "alice", "rock")
# Tuple of mixed data types
mixed_tuple = ("python", 3.14, True)
You can also create a tuple without using parentheses, just separate the items with commas. This is called tuple unpacking.
numbers = 1, 2, 3, 4
names = "james", "bill", "robert"
When creating a tuple with only one element, you must include a trailing comma after the element; otherwise, Python will treat it as a regular value instead of a tuple.
single = (22,) # Tuple
not_tuple = (22) # Integer
The tuple() constructor
The tuple() constructor allows us to create a tuple from an iterable, such as a list, string, set, or dictionary.
For example:
# Empty tuple
empty = tuple()
# Creating a tuple from a list
tuple_from_list = tuple([1, 2, 3])
print(tuple_from_list) # Output: (1, 2, 3)
# Creating a tuple from a string
tuple_from_string = tuple("hello")
print(tuple_from_string) # Output: ('h', 'e', 'l', 'l', 'o')
# Creating a tuple from a set
tuple_from_set = tuple({5, 10, 15})
print(tuple_from_set) # Output: (10, 5, 15)
# Creating a tuple from a dictionary (only keys are included)
tuple_from_dictionary = tuple({"name": "James", "age": 30})
print(tuple_from_dictionary) # Output: ('name', 'age')
Accessing Tuple Items
You can access tuple items using indexing or slicing.
Using Indexing
Every item in a tuple has a position called an index. The first item has the index 0, the second has the index 1 and so on.
To get a specific item, write the name of the tuple followed by the item’s index number inside square brackets [].
For example:
fruits = ("apple", "banana", "mango", "orange")
print(fruits[1]) # Output: banana
print(fruits[2]) # Output: mango
You can also use negative indexes to access items from the end of the tuple. The last item has the index -1, the second-to-last has the index -2, and so on.
fruits = ("apple", "banana", "mango", "orange")
print(fruits[-1]) # Output: orange
print(fruits[-2]) # Output: mango
Using Slicing
You can also get a range of items using tuple slicing. Here is a basic syntax of tuple slicing:
tuple[start:end:step]
Where,
start (Optional): The index where the slice begins. If omitted, slicing starts from the beginning of the tuple.
end (Optional): The index where the slice stops (the items at end index is not included in the result). If omitted, slicing goes to the end of the tuple.
step (Optional) : Determines how many items to skip between each element. The default is 1, which means every item is included.
For example:
fruits = ("apple", "banana", "mango", "orange")
print(fruits[1:3]) # Output: ('banana', 'mango')
In this example, the start index is 1, meaning the slicing will start from the item at index 1. The end index is 3, meaning the slicing will stop just before index 3 (it doen’t include the item at index 3. Therefore, the resulting tuple includes the second and third item: "banana" and "mango".
Here are more examples of tuple slicing:
fruits = ("apple", "banana", "mango", "orange", "pineapple")
# Accessing elements from the beginning up to, but not including, index 3 (start index is omited)
print(fruits[:3]) # Output: ('apple', 'banana', 'mango')
# Accessing elements from index 1 to end of the tuple (end index is omitted)
print(fruits[1:]) # Output: ('banana', 'mango', 'orange', 'pineapple')
# Accessing all elements from start to end (both start and end indexes are omitted)
print(fruits[:]) # Output: ('apple', 'banana', 'mango', 'orange', 'pineapple')
# Accessing every second element of the tuple (step of 2)
print(fruits[::2]) # Output: ('apple', 'mango', 'pineapple')
Tuple Length
You can get the length (number of items) of a tuple using the built-in len() function.
For example:
numbers = (5, 10, 15, 20)
print(len(numbers)) # Output: 4
Tuple Membership Testing
You can check whether an item already exists in a tuple using the in operator.
For example:
numbers = (5, 10, 15, 20)
print(5 in numbers) # Output: True
print(30 in numbers) # Output: False
Looping Through a Tuple
You can iterate over the elements of a tuple using a for loop.
For example:
fruits = ("apple", "banana", "mango", "orange")
for fruit in fruits:
print(fruit)
Output:
apple
banana
mango
orange
If you need to access each element and its index while looping through a tuple, you can use the enumerate() function.
fruits = ("apple", "banana", "mango", "orange")
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
Output:
0: apple
1: banana
2: mango
3: orange
Tuple Unpacking
Tuple unpacking allows you to assign the elements of a tuple to multiple variables in a single statement.
For example:
person = ("James", 30, "London")
name, age, location = person
print(name) # Output: James
print(age) # Output: 30
print(location) # Output: London
Tuple Methods
Tuples support only two built-in methods:
count()
Returns the number of times a specified value appears in the tuple.
For example:
numbers = (5, 10, 5, 10, 5, 15, 20)
print(numbers.count(5)) # Output: 3
print(numbers.count(10)) # Output: 2
index()
Returns the index of the first occurrence of a specified value.
For example:
numbers = (5, 10, 5, 10, 5, 15, 20)
print(numbers.index(5)) # Output: 0
print(numbers.index(10)) # Output: 1
Practical Uses of Tuples
Returning Multiple Values From a Function
You can use tuples to return multiple values from a function and easily unpack them.
For example:
def get_user_info():
name = "James"
age = 30
job = "Actor"
return (name, age, job)
name, age, job = get_user_info()
print(name) # Output: James
print(age) # Output: 30
print(job) # Output: Actor
Using Tuples as Dictionary Keys
In Python, dictionary keys must be immutable and hashable. Tuples are immutable, so they can be used as dictionary keys (only if all their elements are also immutable). Lists cannot be used as dictionary keys because they are mutable.
Tuples are great to use as dictionary keys when you want to link data to multiple values at once. For example, you use tuple to store coordinates on a grid, like (latitude, longitude), and use it to look up a city in a dictionary.
For example:
# Dictionary with tuple keys
locations = {
(40.7128, -74.0060): "New York",
(34.0549, -118.2426): "Los Angeles",
(51.5072, -0.1276): "London"
}
# Accessing a value using a tuple key
print(locations[(40.7128, -74.0060)]) # Output: New York
Data Integrity
Since tuples are immutable, you can use them to store data that shouldn’t change. This makes them useful for things like coordinates, constants, settings, or other values that need to stay the same througout your program.
For example:
DAYS_OF_WEEK = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" )
print(f"{DAYS_OF_WEEK[4]} is awesome") # Output: Friday is awesome