Python Tuples (Tuple)
Tuples are another very important data sequence type in Python. They are very similar to lists, but with one key difference: tuples are immutable.
What is a Tuple?
A tuple is an ordered and immutable collection. Once created, you cannot modify, add, or delete elements in the tuple.
Creating Tuples
Tuples are defined using parentheses (), with elements separated by commas ,.
# Create an empty tuple
empty_tuple = ()
# Tuple containing integers
numbers = (1, 2, 3, 4, 5)
# Tuple containing mixed data types
mixed_tuple = (1, "hello", 3.14, True)
# Can also use tuple() constructor
from_list = tuple([1, 2, 3]) # Create tuple from list
# Parentheses can be omitted when creating
my_tuple = 1, "a", "b" # This is also a tuple
print(my_tuple) # Output: (1, 'a', 'b')Note: Creating a tuple with only one element
If you want to create a tuple containing only one element, you must add a comma , after that element.
single_element_tuple = (42,) # This is a tuple
not_a_tuple = (42) # This is just the integer 42
print(type(single_element_tuple)) # Output: <class 'tuple'>
print(type(not_a_tuple)) # Output: <class 'int'>Accessing Tuple Elements
Accessing tuple elements works exactly the same as with lists, through indexing and slicing.
my_tuple = ('p', 'y', 't', 'h', 'o', 'n')
print(my_tuple[0]) # Output: 'p'
print(my_tuple[-1]) # Output: 'n'
print(my_tuple[1:4]) # Output: ('y', 't', 'h')Tuples are Immutable
This is the core difference between tuples and lists. Any attempt to modify a tuple will result in a TypeError.
my_tuple = (1, 2, 3)
# The following operations will all raise errors
# my_tuple[0] = 99 # TypeError: 'tuple' object does not support item assignment
# my_tuple.append(4) # AttributeError: 'tuple' object has no attribute 'append'
# my_tuple.remove(1) # AttributeError: 'tuple' object has no attribute 'remove'Why Use Tuples?
Since lists are more feature-rich, why do we need tuples?
Data Integrity: Since tuples are immutable, you can ensure their contents won't be accidentally modified during program execution. This makes code safer and more predictable. Perfect for use as constant collections.
Performance Optimization: In most cases, tuples are slightly faster to process than lists and consume less memory.
Can be Used as Dictionary Keys: Because tuples are immutable (hashable), they can be used as dictionary keys. Lists are mutable and cannot be used as dictionary keys.
pythonlocations = { (35.6895, 139.6917): "Tokyo", (40.7128, -74.0060): "New York" }
Tuple Methods
Because tuples are immutable, they have very few methods - only two:
tuple.count(x): Returns the number of times elementxappears in the tuple.tuple.index(x): Returns the index of the first occurrence of elementxin the tuple.
Tuple Unpacking
This is a very convenient and Pythonic feature that allows you to assign elements of a tuple to multiple variables.
# Define a tuple
user_profile = ("John Doe", 30, "john.doe@example.com")
# Unpack
name, age, email = user_profile
print(name) # Output: John Doe
print(age) # Output: 30
print(email) # Output: john.doe@example.comThis feature is particularly useful when functions return multiple values, as a function's multiple return values are actually packaged as a tuple and returned.