123k views
5 votes
Write a function named 'swap' that swaps the first and last elements of a list argument. Given the input: ['all', 'good', 'things', 'must', 'end', 'here'], what will be the output?

1) ['here', 'good', 'things', 'must', 'end', 'all']
2) ['all', 'good', 'things', 'must', 'end', 'here']
3) ['here', 'good', 'things', 'must', 'all', 'end']
4) ['all', 'good', 'things', 'must', 'here', 'end']

1 Answer

2 votes

Final answer:

The function 'swap' exchanges the first and last elements of a list. For the input, the correct output after the swap is ['here', 'good', 'things', 'must', 'end', 'all'].

Step-by-step explanation:

To write a function named 'swap' that swaps the first and last elements of a list, you need to perform a simple exchange of elements at index 0 and index -1. Below is a simple example of how this function could be written in Python:

def swap(lst):
if len(lst) > 1: # Checks if there are at least two elements to swap
lst[0], lst[-1] = lst[-1], lst[0] # Swapping the first and last elements
return lst

For the input list ['all', 'good', 'things', 'must', 'end', 'here'], the output after calling swap would be option 1) ['here', 'good', 'things', 'must', 'end', 'all'], because the first and last elements have been swapped.

The 'swap' function swaps the first and last elements of the list, resulting in the first element 'all' being moved to the last position, and the last element 'here' being moved to the first position.

User Danieldms
by
8.0k points