Given a list, write a Python program to swap the first and last element of the list.
Examples:
Input : [12, 35, 9, 56, 24],
Output :[24, 35, 9, 56, 12]
Input : [1, 2, 3]
Output :[3, 2, 1]
- Python program to swap two elements in a list
Input :List = [23, 65, 19, 90], pos1 = 1, pos2 = 3
Output :[19, 65, 23, 90]
1 Like
def swap_first_and_last(lst):
if len(lst) < 2:
return lst # Nothing to swap for lists with 0 or 1 element
lst[0], lst[-1] = lst[-1], lst[0]
return lst
input1 = [12, 35, 9, 56, 24]
print(“Input:”, input1)
print(“Output:”, swap_first_and_last(input1))
input2 = [1, 2, 3]
print(“Input:”, input2)
print(“Output:”, swap_first_and_last(input2))
-
def swap_elements(lst, pos1, pos2):
if pos1 < 0 or pos2 < 0 or pos1 >= len(lst) or pos2 >= len(lst):
print(“Invalid positions. Cannot swap elements.”)
return
lst[pos1], lst[pos2] = lst[pos2], lst[pos1]
lst = [23, 65, 19, 90]
pos1 = 1
pos2 = 3
print(“Original list:”, lst)
swap_elements(lst, pos1, pos2)
print(“List after swapping elements:”, lst)
1 Like
- def elementswap(list1):
list1[0],list1[-1]=list1[-1],list1[0]
return list1
list1=[12, 35, 9, 56, 24]
elementswap(list1)
2.def elementswap(list1,pos1,pos2):
list1[pos1],list1[pos2]=list1[pos2],list1[pos1]
return list1
list1=[23, 65, 19, 90]
pos1=1
pos2=3
elementswap(list1,pos1-1,pos2-1)
1 Like
@michalganesh141 keep working on
@aravindmurali keep working on.
def elementswap(list1,pos1,pos2):
list1[pos1],list1[pos2]=list1[pos2],list1[pos1]
return list1
list1=[23, 65, 19, 90]
pos1=1
pos2=3
elementswap(list1,pos1-1,pos2-1)
1 Like
- def swap(list1):
list1[0],list1[-1]=list1[-1],list1[0]
return list1
list1=[12, 35, 9, 56, 24]
swap(list1)
2.def swap(list,pos1,pos2):
list[pos1],list[pos2]=list[pos2],list[pos1]
return list
input_list = [23, 65, 19, 90]
pos1 = 1
pos2 = 3original list
output_list = elementswap(list,pos1-1,pos2-1)
print(“Input:”, input_list)
print(“Output:”, output_list)
1 Like
def swaplist(newlist):
size = len(newlist)
temp = newlist[0]
newlist[0] = newlist[size -1]
newlist[size-1]=temp
return newList
newlist = [12, 35, 9, 56, 24]
print(swaplist(newlist))`
1 Like
keep practicing @deepakmoon143
keep practicing @shibuna1205