Python tuple Operations Working
Tuples in Python, being immutable,
have certain operations available for manipulation. While you cannot modify the
elements of a tuple after its creation, you can perform various operations like
concatenation, repetition, and slicing to work with tuples. Here are some
common operations:
Concatenation:
You can
concatenate two or more tuples using the +
operator:
tuple1
= (1, 2, 3)
tuple2
= ('a', 'b', 'c')
concatenated_tuple
= tuple1 + tuple2
print(concatenated_tuple) # Output: (1, 2, 3, 'a', 'b', 'c')
Repetition:
You can
create a new tuple by repeating an existing tuple using the * operator:
original_tuple
= (1, 2, 3)
repeated_tuple
= original_tuple * 3
print(repeated_tuple)
# Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)
Slicing:
As
mentioned earlier, you can use slicing to extract a subset of elements from a
tuple:
my_tuple
= (1, 2, 3, 'a', 'b', 'c')
subset_tuple
= my_tuple[1:4]
print(subset_tuple)
# Output: (2, 3, 'a')
Membership
Test:
You can
use the in operator to check if an element exists in a tuple:
my_tuple
= (1, 2, 3, 'a', 'b', 'c')
print('a' in my_tuple)
# Output: True
print('z' in my_tuple)
# Output: False
Length:
You can
use the len() function to get the length of a tuple:
my_tuple
= (1, 2, 3, 'a', 'b', 'c')
print(len(my_tuple))
# Output: 6
Tuple
Unpacking:
You can
use tuple unpacking to assign values to multiple variables:
my_tuple
= (1, 2, 3, 'a', 'b', 'c')
a,
b, c, *rest = my_tuple
print(a, b, c, rest)
# Output: 1 2 3 ['a', 'b', 'c']
These
operations, along with the inherent properties of tuples, make them versatile
for various use cases, such as storing and manipulating collections of data
where immutability is desirable.
Comments
Post a Comment