0 votes
153 views
in Computer Science by (8.5k points)

The code provided below is intended to swap the first and last elements of a given tuple. However, there are syntax and logical errors in the code.

Rewrite it after removing all errors. Underline all the corrections made.

def swap_first_last(tup)

 if len(tup) < 2:

          return tup

     new_tup = (tup[-1],) + tup[1:-1] + (tup[0])

    return new_tup

result = swap_first_last((1, 2, 3, 4))

print("Swapped tuple: " result)

1 Answer

0 votes
by (56.5k points)
 
Best answer

def swap_first_last(tup):

 if len(tup) < 2:

    return tup

     new_tup = (tup[-1],) + tup[1:-1] + (tup[0],)

    return new_tup

result = swap_first_last((1, 2, 3, 4))

print("Swapped tuple:", result)

...