Tuple Operations and Manipulation
Accessing Tuple Elements
Tuple elements can be accessed using their index, just like in lists. The index starts from 0 for the first element.
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[0]) ## Output: 1
print(my_tuple[2]) ## Output: 3
Tuple Unpacking
Tuples can be unpacked into individual variables, making it easier to work with the data.
coordinates = (10, 20)
x, y = coordinates
print(x) ## Output: 10
print(y) ## Output: 20
Tuple Concatenation
Tuples can be concatenated using the +
operator to create a new tuple.
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
combined_tuple = tuple1 + tuple2
print(combined_tuple) ## Output: (1, 2, 3, 4, 5, 6)
Tuple Repetition
Tuples can be repeated using the *
operator to create a new tuple.
single_tuple = (1, 2)
repeated_tuple = single_tuple * 3
print(repeated_tuple) ## Output: (1, 2, 1, 2, 1, 2)
Tuple Slicing
Tuples support slicing, which allows you to extract a subset of elements.
my_tuple = (1, 2, 3, 4, 5)
sliced_tuple = my_tuple[1:4]
print(sliced_tuple) ## Output: (2, 3, 4)
Tuple Methods
Tuples have a limited set of built-in methods, such as count()
and index()
.
my_tuple = (1, 2, 3, 2, 4)
print(my_tuple.count(2)) ## Output: 2
print(my_tuple.index(3)) ## Output: 2
These operations and manipulations allow you to effectively work with tuples in your Python programs.