Operations with Tuples
Just like with lists, we can
access elements of a tuple using
indices and square brackets, as we are accustomed to.
In the example below, we have used the indices directly or selected only a part of them, then the negative indices and reversing the tuple.
To find the
length of a tuple, we use the well-known function
len().
Analyze the code below, where I displayed some interesting information from the two lists:
The in Operator and the not in Group
Already familiar from lists, these test whether a value is or is not present in the respective data collection.
The result is a boolean, so true (
True) or false (
False).
Above, we checked if certain names (strings) exist in the
pers2 tuple.
Deleting a Tuple
As mentioned, deleting an element/object within a tuple is not allowed.
However, we can
completely delete the tuple using the keyword
del. Test it!
Example:
del pers2.
After this command, of course, you can no longer access the variable
pers2 in the program.
The + and * Operators
Similar to their application to lists, the "
+" operator concatenates two or more tuples, while the "
*" operator multiplies the elements.
Example. Test the program below:
t1 = (1, 2, 3)
t2 = (4, 5)
print(t1 + t2)
print((t1 + t2) * 2)
Obviously, the multiplication must be done with
a natural number, otherwise, we will get an interpretation error.
Proceed to the next page.