About Lesson
Tuple Operations
Tuples support various operations similar to lists, such as concatenation, repetition, and membership tests.
Concatenation:
You can concatenate two or more tuples using the +
operator.
Python
codetuple1 = (1, 2)
tuple2 = (3, 4)
result = tuple1 + tuple2
print(result) # Output: (1, 2, 3, 4)
Repetition:
You can repeat a tuple multiple times using the *
operator.
Python
codetuple3 = (1, 2)
result = tuple3 * 3
print(result) # Output: (1, 2, 1, 2, 1, 2)
Membership Test (in
):
You can check if an element is in the tuple using the in
keyword.
Python
my_tuple = (10, 20, 30)
print(20 in my_tuple) # Output: True
print(40 in my_tuple) # Output: False
Length:
You can get the number of elements in a tuple using the len()
function.
Python
codemy_tuple = (1, 2, 3)
print(len(my_tuple)) # Output: 3