Input a list of numbers and swap element at the even location with the elements at the odd location in python

Here,We are going to write python program to input a list of numbers and swap element at even location with the elements at the odd location in python. We can create the list of numbers and find out even and odd location of elements in list. Even and odd locations are also called as even and odd indices.

Suppose we have a list of numbers called numlist, we will exchange each consecutive even indexes with each other, and also exchange each consecutive odd index with each other.

So, if the input is like [11,22,33,44,55,66,77,88,99], then elements at even location are 22,44,66,88 and elements at odd locations are 11,33,55,77,99. After exchanging the location of list elements ,output will be [’22’, ’11’, ’44’, ’33’, ’66’, ’55’, ’88’, ’77’, ’99’]

Python program to swap elements at even location with elements at odd location

numlist = []
listTot = int(input("Total List Items to enter = "))
for i in range(1, listTot+1):
    value = input("Enter the %d List Item = "  %i)
    numlist.append(value)
print("Original list :",numlist)
s=len(numlist)
if s%2!=0:
    s=s-1
print("Elements at odd location :",numlist[::2])
print("Elements at even location :",numlist[1::2])
for i in range(0,s,2):
    numlist[i],numlist[i+1] = numlist[i+1],numlist[i]
print("List after swapping :",numlist)

Output

Total List Items to enter = 9
Enter the 1 List Item = 11
Enter the 2 List Item = 22
Enter the 3 List Item = 33
Enter the 4 List Item = 44
Enter the 5 List Item = 55
Enter the 6 List Item = 66
Enter the 7 List Item = 77
Enter the 8 List Item = 88
Enter the 9 List Item = 99
Original list : ['11', '22', '33', '44', '55', '66', '77', '88', '99']
Elements at odd location : ['11', '33', '55', '77', '99']
Elements at even location : ['22', '44', '66', '88']
List after swapping : ['22', '11', '44', '33', '66', '55', '88', '77', '99']

Python Examples

T

<