Tuples
A tuple is a collection in Python that is ordered and immutable. This means the items in a tuple cannot be changed, added, or removed after the tuple is created. Tuples are useful when you want to store a collection of values that should not be modified.
Key Features of Tuples
- Ordered: Items in a tuple are stored in a specific order and can be accessed using an index.
- Immutable: Once created, the elements of a tuple cannot be changed.
- Allow Duplicates: Tuples can contain duplicate values.
- Can Contain Different Data Types: Like lists, tuples can store different types of data.
Creating a Tuple
Tuples are created using parentheses () or the tuple() function.
Examples:
Python
Copy
# Empty tuple empty_tuple = () # Tuple with integers numbers = (1, 2, 3) # Tuple with mixed data types mixed_tuple = (1, "hello", 3.14) # Tuple without parentheses (optional) no_parentheses = 1, 2, 3 # Single-element tuple (must include a comma) single_element = (5,)
Accessing Tuple Items
You can access tuple elements using indexing (starting from 0).
Examples:
Python
Copy
fruits = ("apple", "banana", "cherry") # Access the first element print(fruits[0]) # Output: apple # Access the last element using negative index print(fruits[-1]) # Output: cherry
Slicing a Tuple
You can extract a portion of a tuple using slicing.
Examples:
Python
Copy
numbers = (0, 1, 2, 3, 4, 5) # Get elements from index 1 to 4 (exclusive) print(numbers[1:4]) # Output: (1, 2, 3) # Get every second element print(numbers[::2]) # Output: (0, 2, 4)
Tuple Methods
Tuples have only two built-in methods:
Method | Description | Example |
---|---|---|
count(x) | Counts the occurrences of x in the tuple | (1, 2, 2, 3).count(2) → 2 |
index(x) | Returns the index of the first occurrence of x | (1, 2, 3).index(2) → 1 |
Why Use Tuples?
- Immutability: Useful for data that should not be changed (e.g., days of the week, coordinates).
- Performance: Tuples are faster than lists for fixed-size collections.
Packing and Unpacking Tuples
Packing:
You can pack multiple values into a single tuple.
coordinates = (10, 20, 30)
Unpacking:
You can extract the values from a tuple into separate variables.
Python
Copy
x, y, z = coordinates print(x) # Output: 10 print(y) # Output: 20 print(z) # Output: 30
Tuple vs List
Feature | Tuple | List |
---|---|---|
Mutability | Immutable | Mutable |
Syntax | (1, 2, 3) | [1, 2, 3] |
Methods | Limited (count, index) | Many (append, remove, etc.) |
Performance | Faster | Slower for fixed-size data |
Converting Between Tuples and Lists
You can convert a tuple to a list or vice versa.
Examples:
Python
Copy
# Convert tuple to list tuple_data = (1, 2, 3) list_data = list(tuple_data) print(list_data) # Output: [1, 2, 3] # Convert list to tuple list_data = [4, 5, 6] tuple_data = tuple(list_data) print(tuple_data) # Output: (4, 5, 6)