A tuple in Python is an ordered collection of items, similar to a list. It is created by placing items inside parentheses (), separated by commas.
The single most important characteristic of a tuple is that it is immutable. This means that once a tuple is created, you cannot change, add, or remove its elements. This makes tuples a great choice for storing data that you know should not be modified, such as coordinates, configuration settings, or records from a database.
Key Characteristics of Tuples
- Ordered: The items in a tuple have a defined order that will not change.
- Immutable: You cannot change the tuple after it has been created. This is the key difference between a tuple and a list.
- Allows Duplicates: Tuples can contain items with the same value.
- Faster and More Memory-Efficient: Because they are immutable, tuples are slightly faster and use less memory than lists, which can be an advantage in performance-critical applications.
Operations on Tuples
- Concatenation (+): Combines two tuples to create a new tuple.
- Repetition (*): Creates a new tuple by repeating the original tuple's elements.
- Indexing and Slicing: You can access items in a tuple using their index, just like with lists.
- Membership Testing (in, not in): Checks if an item exists within a tuple.
Built-in Functions for Tuples
- len(): Returns the number of items in a tuple.
- sum(): Returns the sum of all items (if they are all numbers).
- min() / max(): Returns the minimum or maximum item.
- sorted(): Returns a new, sorted list from the items in the tuple (it does not return a tuple).
Tuple Methods
Because tuples are immutable, they have very few methods. They lack methods like .append(), .remove(), or .sort() that would modify the tuple.
- .count(item): Returns the number of times a specified item appears in the tuple.
- .index(item): Returns the index of the first occurrence of a specified item.
# --- 1. Tuple Creation ---
# Tuples are ordered, immutable collections of items in parentheses.
empty_tuple = ()
# A tuple with one item needs a trailing comma.
single_item_tuple = (1,)
fruits_tuple = ("apple", "banana", "cherry", "apple")
mixed_tuple = (1, "hello", 3.14, True)
print(f"A tuple of fruits: {fruits_tuple}")
print(f"A single item tuple: {single_item_tuple}")
# --- 2. Basic Operations ---
print("\n--- Basic Operations ---")
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
# Concatenation (+) creates a new tuple.
combined_tuple = tuple1 + tuple2
print(f"Concatenation: {combined_tuple}")
# Repetition (*) creates a new tuple.
repeated_tuple = tuple1 * 3
print(f"Repetition: {repeated_tuple}")
# --- 3. Indexing and Slicing ---
# Accessing items in a tuple works just like with lists.
numbers_tuple = (10, 20, 30, 40, 50, 60)
print("\n--- Indexing and Slicing ---")
print(f"Original Tuple: {numbers_tuple}")
print(f"First item (index 0): {numbers_tuple[0]}")
print(f"Last item (index -1): {numbers_tuple[-1]}")
print(f"Slice from index 2 to 4: {numbers_tuple[2:5]}")
# --- 4. Immutability Demonstration ---
# The key feature of a tuple is that it cannot be changed.
print("\n--- Immutability ---")
# The following line would cause a TypeError if uncommented:
# fruits_tuple[1] = "blueberry"
print("Tuples are immutable. You cannot change their elements.")
# --- 5. Tuple Methods ---
# Tuples have very few methods because they are immutable.
print("\n--- Tuple Methods ---")
print(f"Original tuple: {fruits_tuple}")
# .count() returns the number of times an item appears.
print(f"Count of 'apple': {fruits_tuple.count('apple')}")
# .index() returns the index of the first occurrence of an item.
print(f"Index of 'cherry': {fruits_tuple.index('cherry')}")
# --- 6. Built-in Functions with Tuples ---
print("\n--- Built-in Functions with Tuples ---")
numbers = (5, 2, 8, 1, 9)
print(f"Length of numbers tuple: {len(numbers)}")
print(f"Sum of numbers tuple: {sum(numbers)}")
print(f"Max of numbers tuple: {max(numbers)}")
print(f"Min of numbers tuple: {min(numbers)}")
# sorted() returns a new sorted LIST, not a tuple.
sorted_list_from_tuple = sorted(numbers)
print(f"Original tuple: {numbers}")
print(f"New sorted list from tuple: {sorted_list_from_tuple}")
# --- 7. Tuple Unpacking ---
# A powerful feature where you can assign the items of a tuple to variables.
point = (10, 20, 30)
x, y, z = point
print("\n--- Tuple Unpacking ---")
print(f"x = {x}, y = {y}, z = {z}")