+ 1

Input a list of numbers and swap elements at the even location with the elements at the odd location.please tell any other appro

'val=eval(input("Enter a list ")) print("Original List is:",val) s=len(val) if s%2!=0: s=s-1 for i in range(0,s,2): val[i],val[i+1]=val[i+1],val[i] print("List after swapping :",val)

30th Jan 2022, 5:12 PM
Aditya Pradhan
Aditya Pradhan - avatar
3 odpowiedzi
+ 4
Aditya Pradhan , the input for your code is not working, the rest is ok. a different approach could be: iterate trough the list and swap the elements between the positions as demonstrated: lst = [int(i) for i in input().split(",")] for pos in range(0, len(lst), 2): lst[pos], lst[pos +1] = lst[pos +1], lst[pos] print(lst) # input: 1,2,3,4,5,6 # result: [2, 1, 4, 3, 6, 5]
30th Jan 2022, 9:14 PM
Lothar
Lothar - avatar
+ 1
Yes, don't use eval. Why the use of eval? val = input("Enter some stuff: ").split() # <--- it's a list now
30th Jan 2022, 6:25 PM
Slick
Slick - avatar