Ask Question
19 December, 07:47

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. 19 December, 08:51
    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.
  2. 19 December, 11:39
    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.
Know the Answer?
Not Sure About the Answer?
Get 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 there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers