Tuples:
Tuples in Python
A tuple is an immutable sequence type in Python that can hold a collection of items. Tuples are similar to lists, but they cannot be changed after their creation. Unlike of lists, tuples are immutable.
Creating Tuples
Using Parentheses
# Creating an empty tuple
empty_tuple = ()
# Creating a tuple with elements
my_tuple = (1, 2, 3)
Without Parentheses
# Creating a tuple without parentheses
my_tuple = 1, 2, 3
Using the Tuple Constructor
# Creating a tuple from a list
my_tuple = tuple([1, 2, 3])
Single Element Tuple
# Creating a single element tuple
single_element_tuple = (1,)
Major Operations on Tuples
Accessing Elements
# Accessing elements by index
my_tuple = (1, 2, 3)
print(my_tuple[0]) # Output: 1
print(my_tuple[-1]) # Output: 3
Slicing
# Slicing a tuple
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[1:3]) # Output: (2, 3)
print(my_tuple[:3]) # Output: (1, 2, 3)
print(my_tuple[3:]) # Output: (4, 5)
Concatenation
# Concatenating tuples
tuple1 = (1, 2)
tuple2 = (3, 4)
result = tuple1 + tuple2
print(result) # Output: (1, 2, 3, 4)
Repetition
# Repeating a tuple
my_tuple = (1, 2)
result = my_tuple * 3
print(result) # Output: (1, 2, 1, 2, 1, 2)
Checking Membership
# Checking if an element exists in a tuple
my_tuple = (1, 2, 3)
print(2 in my_tuple) # Output: True
print(4 in my_tuple) # Output: False
Iterating Through a Tuple
# Iterating through a tuple
my_tuple = (1, 2, 3)
for item in my_tuple:
print(item)
Unpacking Tuples
# Unpacking elements of a tuple
my_tuple = (1, 2, 3)
a, b, c = my_tuple
print(a) # Output: 1
print(b) # Output: 2
print(c) # Output: 3
Tuple Methods
Count
# Counting occurrences of an element in a tuple
my_tuple = (1, 2, 2, 3)
print(my_tuple.count(2)) # Output: 2
Index
# Finding the index of an element in a tuple
my_tuple = (1, 2, 3)
print(my_tuple.index(2)) # Output: 1
Example
Here is a complete example demonstrating various operations on tuples:
# Creating tuples
empty_tuple = ()
single_element_tuple = (1,)
my_tuple = (1, 2, 3, 4, 5)
# Accessing elements
print(my_tuple[0]) # Output: 1
print(my_tuple[-1]) # Output: 5
# Slicing
print(my_tuple[1:3]) # Output: (2, 3)
# Concatenation
tuple1 = (1, 2)
tuple2 = (3, 4)
result = tuple1 + tuple2
print(result) # Output: (1, 2, 3, 4)
# Repetition
result = my_tuple * 2
print(result) # Output: (1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
# Checking membership
print(2 in my_tuple) # Output: True
print(6 in my_tuple) # Output: False
# Iterating through a tuple
for item in my_tuple:
print(item)
# Unpacking
a, b, c, d, e = my_tuple
print(a) # Output: 1
print(b) # Output: 2
print(c) # Output: 3
print(d) # Output: 4
print(e) # Output: 5
# Tuple methods
print(my_tuple.count(2)) # Output: 1
print(my_tuple.index(3)) # Output: 2