0 votes
in Python by
Can you write a function in Python to swap the elements in a Tuple?

1 Answer

0 votes
by

Yes, swapping elements in a tuple is possible in Python. Tuples are immutable, meaning their values cannot be changed directly. However, we can convert the tuple into a list, perform the swap operation, and then reconvert it back to a tuple.

Here’s an example function that swaps the first and last elements of a tuple:

def swap_tuple_elements(t):

    if len(t) < 2:

        return t

    else:

        swapped_list = list(t)

        swapped_list[0], swapped_list[-1] = swapped_list[-1], swapped_list[0]

        return tuple(swapped_list)

In this function, ‘t’ is the input tuple. The function checks if the length of the tuple is less than 2. If so, it returns the original tuple as there are not enough elements to swap. Otherwise, it converts the tuple to a list, performs the swap, and converts the list back to a tuple before returning it.

Related questions

+1 vote
asked Oct 28, 2022 in Python by SakshiSharma
0 votes
asked Sep 7, 2022 in Python by sharadyadav1986
...