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)


2.Tuple Slicing:

Similar to lists, tuples support slicing operations to extract a portion of the tuple.

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

 
3.Iterating Over a Tuple

You can use a for loop to iterate over the elements of a tuple.
my_tuple = (1, 2, 3) for element in my_tuple: print(element)
Output: 1 2 3

4.Tuple to List Conversion and Vice Versa:

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)


Tuples are commonly used when you want to store a collection of elements that should not be modified. They can be used as keys in dictionaries and as elements of sets, among other use cases.

Comments