-1

Write a function swap that swaps the first and last elements of a list argument.

Sample output with input: 'all,good,things,must,end,here'

['here', 'good', 'things', 'must', 'end', 'all']

def swap (values_list):
    values_list[0] = values_list[-1]
    values_list[-1] = values_list[0]
    return values_list

values_list = input().split(',')  # Program receives comma-separated values like 5,4,12,19
swap(values_list)

print(values_list)

Here is the image that my output is wrong:

Julian
  • 5,290
  • 1
  • 17
  • 40
AwayB
  • 9
  • 1

2 Answers2

1

This should work.

What you did was make item 0 the last item with the first statement, then made the last item the first item which was just made the last item.

You need to swap both items at the same time, or store them in a temp variable first, then swap them.

def swap (values_list):
    temp0 = values_list[0]
    temp1 = values_list[-1]
    values_list[0] = temp1
    values_list[1] = temp0
    return values_list

values_list = input().split(',')  # Program receives comma-separated values like 5,4,12,19
swap(values_list)

print(values_list)

The syntax in the link below is used to swap 2 items in a list. It's a one liner. You should read it, it has some good examples.

https://www.geeksforgeeks.org/python-program-to-swap-two-elements-in-a-list/

newbie01
  • 136
  • 4
0

Correction to the last assignment of values_list[] to include -1 instead of 1.

    def swap (values_list):
        temp0 = values_list[0]
        temp1 = values_list[-1]
        values_list[0] = temp1
        values_list[-1] = temp0
        return values_list
rb5064
  • 1