Python Tuple
A tuple is a built-in data type used to store multiple items in a single variable. It is similar to a list, but unlike lists, tuples are immutable, meaning their contents cannot be modified after creation. You use tuples to store collections of values that remain constant throughout the program.
Characteristics of Python Tuples
- Ordered: Tuples maintain the order in which elements are inserted.
- Immutable: Once a tuple is created, its elements cannot be modified, added, or removed.
- Heterogenous: Tuples can store elements of different data types.
- Allow Duplicates: Tuples can store duplicate values.
Creating Tuples
You can create a tuple by placing values inside parentheses ()
separated by commas.
For example:
my_tuple = (1, 2, 3)
Parentheses are optional when creating a tuple; simply separating values with commas will create a tuple.
For example:
my_tuple = 1, 2, 3
Creating tuples using the tuple()
Constructor
You can also create a tuple from an iterable (like a list or string) using the tuple()
constructor.
For example:
# Creating a tuple from a list
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple) # Output: (1, 2, 3)
# Creating a tuple from a string
my_str = "python"
my_tuple = tuple(my_str)
print(my_tuple) # ('p', 'y', 't', 'h', 'o', 'n')
Creating a Tuple with One Element
To create a tuple with only one element, you must include a trailing comma. Without the comma, Python will interpret the value as a regular data type, not a tuple.
For example:
single_element_tuple = (5,)
print(single_element_tuple) # Output: (5,)
print(type(single_element_tuple)) # Output: <class 'tuple'>
# Without the comma
not_a_tuple = (5)
print(not_a_tuple) # Output: 5
print(type(not_a_tuple)) # Output: <class 'int'>
The type()
function returns the type of the object.
Creating an Empty Tuple
You can create an empty tuple using empty parentheses.
For example:
empty_tuple = ()
print(empty_tuple) # Output: ()
You can also create an empty tuple using the tuple()
constructor without any arguments.
empty_tuple = tuple()
print(empty_tuple) # Output: ()
Accessing Tuple Elements
To access tuple elements, you can use the name of the tuple followed by the index of the desired element inside square brackets. Python tuple uses zero-based indexing, meaning the first element is at index 0
, the second element is at index 1
, and so on.
For example:
my_tuple = ("apple", "banana", "pineapple")
# Accessing the first element
print(my_tuple[0]) # Output: apple
# Accessing the second element
print(my_tuple[1]) # Output: banana
Negative Indexing
Python tuples also support negative indexing, which allows you to access elements from the end of the tuple. The last element is at index -1
, the second last index -2
, and so on.
For example:
my_tuple = ("apple", "banana", "pineapple")
# Accessing the last element
print(my_tuple[-1]) # Output: pineapple
# Accessing the second last element
print(my_tuple[-2]) # Output: banana
Tuple Slicing
Tuple slicing allows you to extract a portion of a tuple by specifying a range of indices.
The syntax for slicing a tuple is:
tuple[start:end:step]
start
(Optional): The index where the slice starts (inclusive). If omitted, it defaults to the beginning of the tuple (index 0
).
end
(Optional): The index where the slice ends (exclusive). If omitted, it defaults to the end of the tuple.
step
(Optional): The step size between elements. If omitted, it defaults to 1
.
For example:
my_tuple = ("apple", "banana", "pineapple", "orange")
# Access elements from index 0 to 2 (excluding the element at index 2)
print(my_tuple[0:2]) # Output: ('apple', 'banana')
# Access all elements starting from index 1
print(my_tuple[1:]) # Output: ('banana', 'pineapple', 'orange')
# Access all elements up to, but not including the last element
print(my_tuple[:-1]) # Output: ('apple', 'banana', 'pineapple')
# Access all elements from start to end
print(my_tuple[:]) # Output: ('apple', 'banana', 'pineapple', 'orange')
# Access elements with a step of 2 (every second element)
print(my_tuple[::2]) # Output: ('apple', 'pineapple')
Tuple Unpacking
Tuple unpacking is a feature in Python that allows you to assign the elements of a tuple to multiple variables in a single statement.
For example:
my_tuple = (5, 10, 15)
# Tuple unpacking
a, b, c = my_tuple
print(a) # Output: 5
print(b) # Output: 10
print(c) # Output: 15
Iterating Through Tuples
You can use a for
loop to iterate over the elements of a tuple.
For example:
my_tuple = (5, 10, 15)
for item in my_tuple:
print(item)
Output:
5
10
15
Using enumerate()
If you need the index along with the value, you can use the enumerate()
function.
For example:
my_tuple = ('a', 'b', 'c')
for index, value in enumerate(my_tuple):
print(f"Index: {index}, Value: {value}")
Output:
Index: 0, Value: a
Index: 1, Value: b
Index: 2, Value: c
Nested Tuples
Nested tuples are tuples that contain other tuples as their elements.
For example:
nested_tuple = ((1, 2), (3, 4), (5, 6))
You can access elements in a nested tuple using indexing.
For example:
nested_tuple = (("apple", "banana"), ("pumpkin", "potato"))
print(nested_tuple[0][0]) # Output: apple
print(nested_tuple[0][1]) # Output: banana
print(nested_tuple[1][0]) # Output: pumpkin
print(nested_tuple[1][1]) # Output: potato
Tuple Methods
In Python, tuples are immutable, so they have only two methods.
Method | Description |
count() | Returns the number of times a specified value appears in the tuple. |
index() | Returns the first index where a specified value is found. Raises an error if not found. |
Tuples vs Lists
Here are the key differences between tuples and lists:
Feature | Tuple | List |
Mutability | Immutable (cannot change) | Mutable (can change) |
Syntax | (1, 2, 3) | [1, 2, 3] |
Performance | Faster | Slower |
Use Case | Fixed data (e.g., cooridinates) | Modifiable data (e.g., Dynamic lists) |