Python Program to Swap Elements Between Two Lists

Python Program to Swap Elements Between Two Lists | Swapping refers to the exchange elements, this is usually done with the list. In this section, we see methods to python swap elements between two lists. The list is a container that stores elements of similar data types.

Swap Elements Between Two Lists in Python

Here, we will see how to swap elements between two lists. In the below code we initialize the first list to integer values and the second list to a string.

Program description:- Write a python program to swap elements between two lists

# Python Program to swap elements between two list

# take inputs
l1 = [1, 2, 3, 4, 5]
l2 = ['a', 'b', 'c', 'd', 'e']

# print list
print("List1:", l1)
print("List2:", l2)

# swap elements
l1[1] , l2[2] = l2[2], l1[1]

# print new list
print("New List")
print("List1:", l1)
print("List2:", l2)

Output:-

List1: [1, 2, 3, 4, 5]
List2: [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
New List
List1: [1, ‘c’, 3, 4, 5]
List2: [‘a’, ‘b’, 2, ‘d’, ‘e’]

Here, we are trying to swap the second element of the first list with the third element of the first list, hence the output will be as follows.

Python Program to Swap Elements Between Two Lists

In the previous program, swap positions in lists are hardcoded in the program but in this program, the positions will be given by the user.

# Python Program to swap elements between two list

# take inputs
l1 = [1, 2, 3, 4, 5]
l2 = ['a', 'b', 'c', 'd', 'e']

# print list
print("List1:", l1)
print("List2:", l2)

# take swap position in list
p1 = int(input("Enter Position in List1: "))
p2 = int(input("Enter Position in List2: "))

# swap elements
l1[p1] , l2[p2] = l2[p2], l1[p1]

# print new list
print("New List")
print("List1:", l1)
print("List2:", l2)

Output for the input values test-case-1:-

List1: [1, 2, 3, 4, 5]
List2: [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
Enter Position in List1: 1
Enter Position in List2: 1
New List
List1: [1, ‘b’, 3, 4, 5]
List2: [‘a’, 2, ‘c’, ‘d’, ‘e’]

Output for the input values test-case-2:-

List1: [1, 2, 3, 4, 5]
List2: [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
Enter Position in List1: 4
Enter Position in List2: 3
New List
List1: [1, 2, 3, 4, ‘d’]
List2: [‘a’, ‘b’, ‘c’, 5, ‘e’]

Output for the input values test-case-3:-

List1: [1, 2, 3, 4, 5]
List2: [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
Enter Position in List1: 2
Enter Position in List2: 4
New List
List1: [1, 2, ‘e’, 4, 5]
List2: [‘a’, ‘b’, ‘c’, ‘d’, 3]

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published.