C_WJ
C_WJ

Reputation: 15

Python difference between a list and multi-dimensional list

I need some help, the following is what I want:

list1 = [["a", "1"], ["b", "2"], ["c", "3"], ["d", "4"]]
list2 = ["b", "c"]
list3 = []

list1 - list2 = list3
print(list3)

Expected Output:
[["a", "1"], ["d", "4"]]

I know that you can do the following with one-dimensional lists:

list1 = ["a", "b", "c", "d"]
list2 = ["b", "c"]

list3 = list(set(list1) - set(list2))
print(list3)

Output: ["a", "d"]

So, how do I do the above but with multi-dimensional lists and output of a multi-dimensional list as well?

Upvotes: 0

Views: 132

Answers (3)

Celius Stingher
Celius Stingher

Reputation: 18377

You can try with list comprehension. Essentially what we are doing is, retaining the sublists from list1 that their first value (the character) does not exists in the values of list2:

list1 = [["a", "1"], ["b", "2"], ["c", "3"], ["d", "4"]]
list2 = ["b", "c"]

list3 = [item for item in list1 if item[0] not in list2]
print(list3)

Output:

[['a', '1'], ['d', '4']]

However this is to solve this particular example with the particular data you provide. As explained in comments, working with dictionaries is recommended.

Upvotes: 1

Grégoire Roussel
Grégoire Roussel

Reputation: 947

G. Anderson is right, it seems that you're in a good use case for dictionnaries.

If you'll stuck with this data structure (that could be the case if your inner lists can have more than 2 elements), you'll have to use list comprehension, this syntax is not supported out-of-the-box.

my suggestion

list1 = [["a", "1"], ["b", "2"], ["c", "3"], ["d", "4"]]
ignored_keys = ['b', 'c']
list3 = [val for val in list1 if val[0] not in ignored_keys]
print(list3)
Output: [['a', '1'], ['d', '4']]

Upvotes: 1

danetrata
danetrata

Reputation: 9

Here's another answer using filter and a lambda function.

list1 = [["a", "1"], ["b", "2"], ["c", "3"], ["d", "4"]]
list2 = ["b", "c"]
list3 = []

list3 = list(filter(lambda x: x[0] not in list2, list1))
print(list3)

# [["a", "1"], ["d", "4"]]

Upvotes: 1

Related Questions