Tuples in Python
Tuples in Python
1. Ordered
o Tuples maintain the order of elements. Once created, the order does not
change.
o Example:
2. Immutable
o Tuples cannot be modified after creation. You cannot add, remove, or change
elements in a tuple.
o Example:
my_tuple = (1, 2, 3)
# my_tuple[1] = 20 # This will raise a TypeError
3. Heterogeneous
o Tuples can store elements of different data types, such as integers, strings,
floats, and even other tuples.
o Example:
4. Supports Nesting
o Tuples can contain other tuples or any other collection type (e.g., lists or
dictionaries).
o Example:
5. Indexed
o Tuples use zero-based indexing to access their elements.
o Example:
6. Iterable
o Tuples can be iterated over using loops or comprehensions.
o Example:
my_tuple = (1, 2, 3)
for item in my_tuple:
print(item)
7. Hashable
o Tuples are hashable, meaning they can be used as keys in dictionaries or
elements in sets (only if all elements within the tuple are hashable).
o Example:
my_tuple = (1, 2, 2, 3)
print(my_tuple.count(2)) # Output: 2
print(my_tuple.index(3)) # Output: 3
my_tuple = (1, 2, 2, 3)
print(my_tuple) # Output: (1, 2, 2, 3)
Advantages of Tuples
In Python, an element is hashable if it has a fixed hash value that does not change during its lifetime.
This means it can be used as a key in dictionaries or an element in sets, which require elements to
be uniquely identifiable.
Hash Function
Example:
Immutability
For an element to be hashable, it must be immutable. This ensures that its hash value
remains constant.
Examples of immutable types:
o Numbers: int, float
o Strings: str
o Tuples (if all elements inside are hashable)
Examples of non-hashable types:
o Lists: list (mutable)
o Dictionaries: dict (mutable)
o Sets: set (mutable)
Here are the operations you can perform on tuples in Python, with examples:
1. Accessing Elements
a. Indexing
b. Slicing
3. Concatenation
tuple1 = (1, 2)
tuple2 = (3, 4)
result = tuple1 + tuple2
print(result) # Output: (1, 2, 3, 4)
4. Repetition
my_tuple = (1, 2)
print(my_tuple * 3) # Output: (1, 2, 1, 2, 1, 2)
5. Membership Testing
7. Counting Elements
Use the index() method to find the first occurrence of a value in a tuple.
a. Packing
a, b, c = (1, 2, 3)
print(a) # Output: 1
print(b) # Output: 2
print(c) # Output: 3
Sort the elements of a tuple. Since tuples are immutable, you need to convert them into a list
first.
Tuples are immutable, so you cannot modify, add, or remove elements. Attempting to do so
raises an error.
To create a tuple with one element, you must include a trailing comma.
single_element_tuple = (42,)
print(type(single_element_tuple)) # Output: <class 'tuple'>
Tuples are hashable and can be used as dictionary keys (if they contain only hashable
elements).
Use the * operator to join tuples inside another tuple using unpacking.
tuple1 = (1, 2, 3)
tuple2 = (4, 5)
combined = (*tuple1, *tuple2)
print(combined) # Output: (1, 2, 3, 4, 5)