1. What is a Tuple in Python?
A tuple is a collection data type in Python that is ordered and immutable. It means that once a tuple is created, you cannot change its elements. Tuples are defined by enclosing the elements in parentheses `()`.
# Creating a tuple
my_tuple = (1, 2, 3, 'a', 'b', 'c')
# Displaying the tuple
print(my_tuple)
2. Access Tuple Items:
You can access elements of a tuple using indexing. Indexing starts from 0 for the first element.
# Accessing elements of a tuple
print(my_tuple[0]) # Output: 1
print(my_tuple[3]) # Output: 'a'
3. Update Tuple:
Since tuples are immutable, you cannot change their elements. However, you can create a new tuple with updated values.
# Updating a tuple (creating a new tuple)
updated_tuple = my_tuple + (4, 5, 'd')
# Displaying the updated tuple
print(updated_tuple)
4. Unpack Tuple:
You can unpack the values of a tuple into variables.
# Unpacking tuple values
a, b, c, *rest = my_tuple
# Displaying the unpacked values
print(a, b, c) # Output: 1 2 3
print(rest) # Output: ['a', 'b', 'c']
5. Loop Through Tuple:
You can use a loop to iterate over the elements of a tuple.
# Looping through a tuple
for item in my_tuple:
print(item)
6. Join Tuples:
You can concatenate or join two tuples using the `+` operator.
# Joining two tuples
tuple1 = (1, 2, 3)
tuple2 = ('a', 'b', 'c')
joined_tuple = tuple1 + tuple2
# Displaying the joined tuple
print(joined_tuple)
7. Tuple Methods:
Tuples have several built-in methods. One commonly used method is `count()` to count occurrences of a specific element, and another is `index()` to find the index of a specific element.
# Using tuple methods
my_tuple = (1, 2, 3, 'a', 'b', 'a', 'c')
# Count occurrences of 'a'
count_a = my_tuple.count('a')
print("Count of 'a':", count_a)
# Find the index of 'b'
index_b = my_tuple.index('b')
print("Index of 'b':", index_b)
These are the basic operations you can perform with tuples in Python. Remember, tuples are useful when you want to store a collection of items that should not be changed during the program execution.