Swap two adjacent item in list in python by R4R Team

Example-

list is [1,2,3,4,5,6]

Aim to convert this list in [2,1,4,3,6,5]


program-

print("Enter number in list")
l=list(map(int,input().split()))

print("List is",l)
i=0
while(i<'len(l)):
l[i],l[i+1]=l[i+1],l[i]
i+=2

print("List become",l)


output-

Enter number in list
1 2 3 4 5 6
List is [1, 2, 3, 4, 5, 6]
List become [2, 1, 4, 3, 6, 5]

Enter number in list
87 65 34 12 6 5
List is [87, 65, 34, 12, 6, 5]
List become [65, 87, 12, 34, 5, 6]


-In this program, we take an input of the list, then by using while we iterate the list and increase the value of i by 2 so that we deals with the two-two elements in the list.




Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!