Tuples in Python
Hey there! In this guide, we'll explore tuples in Python. Tuples are ordered, immutable collections of elements that allow you to store and manipulate data efficiently. Let's dive in!
Python Tuples​
- Ordered: Elements have a defined order and can be accessed via indices.
- Immutable: Once created, elements in a tuple cannot be changed.
- Heterogeneous: Tuples can store elements of different data types (e.g., integers, strings, booleans).
- Supports nesting: Tuples can contain other tuples or lists as elements.
1. Creating a Tuple​
You can create a tuple using parentheses ()
or the tuple()
function.
my_tuple = (1, 2, 3, 4, 5) # Create a tuple using parentheses
another_tuple = tuple(('apple', 'banana', 'cherry')) # Create a tuple using the tuple() function
print(my_tuple) # Output: (1, 2, 3, 4, 5)
print(another_tuple) # Output: ('apple', 'banana', 'cherry')
2. Accessing Elements​
You can access elements in a tuple using their index. Python uses zero-based indexing.
my_tuple = (10, 20, 30, 40, 50)
print(my_tuple[0]) # Access the first element, Output: 10
print(my_tuple[3]) # Access the fourth element, Output: 40
3. Unpacking Tuples​
You can unpack a tuple by assigning its elements to multiple variables.
my_tuple = (1, 2, 3)
a, b, c = my_tuple # Unpacking tuple elements
print(a) # Output: 1
print(b) # Output: 2
print(c) # Output: 3
4. Tuple Methods​
Tuples have only two built-in methods: count()
and index()
.
my_tuple = (1, 2, 2, 3, 4, 2)
count_of_twos = my_tuple.count(2) # Count the number of occurrences of a value
print(count_of_twos) # Output: 3
index_of_three = my_tuple.index(3) # Get the index of the first occurrence of a value
print(index_of_three) # Output: 3
5. Nested Tuples​
Tuples can contain other tuples or lists as elements.
nested_tuple = (1, (2, 3), [4, 5]) # A tuple with a nested tuple and a list
print(nested_tuple) # Output: (1, (2, 3), [4, 5])