TUPLES
Certainly! Here's some additional information about tuples in Python:
1.Immutable Nature:
Tuples are immutable, which means that once a tuple is created, you cannot modify its elements. However, you can create a new tuple with modified or additional elements.
Example:
my_tuple = (1, 2, 3) # Attempting to modify the tuple will result in an error my_tuple[0] = 4 # Raises Type Error: 'tuple' object does not support item assignment # Creating a new tuple with modified elements modified_tuple = (4,) + my_tuple[1:] print(modified_tuple)
Output: (4, 2, 3)
Example:
my_tuple = (1, 2, 3, 4, 5) sliced_tuple = my_tuple[1:4] print(sliced_tuple)
Output: (2, 3, 4)
You can determine the length of a tuple using the len()
function. The in
and not in
operators can be used to check if an element is present in the tuple.
Example:
my_tuple = (1, 2, 3) print(len(my_tuple)) # Output: 3 print(2 in my_tuple) # Output: True print(4 not in my_tuple) # Output: True
for
loop to iterate over the elements of a tuple.You can convert a tuple to a list using the list()
function and vice versa using the tuple()
function.
Example:
my_tuple = (1, 2, 3) my_list = list(my_tuple) print(my_list)
Output: [1, 2, 3]
Example:
another_tuple = tuple(my_list) print(another_tuple)
Output: (1, 2, 3)
Comments
Post a Comment