Ask Question
2 November, 08:11

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']

+1
Answers (2)
  1. 2 November, 08:13
    0
    li=list (map (str, input (). strip (). split ())) #taking input of the string.

    #swapping first and last element.

    temp=li[0]

    li[0]=li[-1]

    li[-1]=temp

    print (li) #printing the list.

    Explanation:

    I have taken the list li for taking the input of strings. Then after that swapping first and last element of the list. Then printing the list.
  2. 2 November, 08:32
    0
    def swap (li):

    n=len (li)

    li[0], li[n-1]=li[n-1], li[0]

    return li

    Explanation:

    Python is very user friendly language and and this provides numerous functions and in-built services. In the above function, i have created a method which is taking an argument li and we can find the length of li by using method len () which is then stored in variable n. Now we have to swap first and last element so, first element of li is li[0] and last is li[n-1]. Python provides one more utility in which we can change values of 2 elements simultaneously by separating them with comma. So, we put the value of last element in first and value of first in last which saved many lines of code.
Know the Answer?
Not Sure About the Answer?
Find an answer to your question 👍 “Write a function swap that swaps the first and last elements of a list argument. Sample output with input: 'all, good, things, must, end, ...” in 📗 Computers & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers