1

I want to swap every occurrence of two elements in a list of lists. I have seen previous answers but they are different from what I'm trying to do. Also, I am looking for a clean and concise way (preferably list-comprehension) for this purpose.

Input

my_list = [[1,2], [1,3], [1,4], [3,2]]

Output

my_list = [[2,1], [2,3], [2,4], [3,1]]

I am trying to do something like this but no success:

[1 if i==2 else i, 2 if i==1 else i for i in my_list]
4
  • 1
    Can you please clarify why is the output [[2,1], [2,3], [2,4], [3,1]] as opposed to [[2, 1], [3, 1], [4, 1], [2, 3]]? Commented Sep 21, 2020 at 4:18
  • 2
    @joe733 op wants to swap every occurrence of 1 with 2 and vice-versa Commented Sep 21, 2020 at 4:21
  • @heitor oh I see, thanks! Commented Sep 21, 2020 at 4:22
  • @heitor See my updated answer. Commented Sep 21, 2020 at 7:01

3 Answers 3

3

Here's a simple solution using list comprehension:

my_list = [[1,2], [1,3], [1,4], [3,2]]

a = 1
b = 2
my_list = [[a if i==b else b if i==a else i for i in j] for j in my_list]

print(my_list) # [[2, 1], [2, 3], [2, 4], [3, 1]]

If you want to add more elements to replace you can use a dictionary:

swap = {
    1: 2,
    2: 1
}

my_list = [[swap.get(i, i) for i in j] for j in my_list]
Sign up to request clarification or add additional context in comments.

Comments

1

Someone else will probably answer with something better, but this would work.

def check(num):
    if num == 1:
        return 2
    elif num == 2:
        return 1
    else:
        return num

out = [[check(j) for j in i] for i in my_list]

Comments

0

If you need to swap 1's with 2's, this one-liner will work:

>>> my_list = [[1,2], [1,3], [1,4], [3,2]]
>>> print([[(lambda k: (1 if val == 2 else 2) if val in [1, 2] else val)(val) for val in sub_list] for sub_list in my_list])
[[2, 1], [2, 3], [2, 4], [3, 1]]

read the second line from right to left... in chunks!

2 Comments

This code is interchanging the positions of elements in sub-lists, the original question is asking something different. That is to replace 1 with 2 and 2 with 1 throughout the list.
The headline is a bit misguiding. I clarified my doubt from the comments below the question. I've updated my answer to meet op's requirements. Thanks anyway!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.