Tirumala
Tirumala

Reputation: 49

How to remove multiple lists from the multiple lists?

I have two lists:

l1 = [[1,2,3,4,5], [1,2,4,6,7]]
l2 = [[1,2,3,4,5], [1,2,4,6,7], [1,2,3,6,8], [1,2,3,0,9], [1,2,6,7,6]]

I want to create a new list l3 that contains the items of l2 that are not in l1. Something like this:

l3 = l2-l1

So, I am expecting an l3 as:

l3 = [[1,2,3,6,8], [1,2,3,0,9], [1,2,6,7,6]]

How can I achieve that? Any solution Using remove() or delete() in python..?

Upvotes: 0

Views: 531

Answers (7)

>>> l1 = [[1,2,3,4,5],[1,2,4,6,7]]
>>> l2 = [[1,2,3,4,5],[1,2,4,6,7],[1,2,3,6,8],[1,2,3,0,9],[1,2,6,7,6]]
>>> for i in l1:
>>> if i in l2:
>>>     del l2[l2.index(i)]
>>> print(l2)

Upvotes: 0

neehari
neehari

Reputation: 2612

If you want to remove l2 sublists that are in l1 and create a new list with the remaining sublists, try this:

l1 = [[1,2,3,4,5], [1,2,4,6,7]]
l2 = [[1,2,3,4,5], [1,2,4,6,7], [1,2,3,6,8], [1,2,3,0,9], [1,2,6,7,6]]

for sub in l1:
    if sub in l2:
        l2.remove(sub)

l3 = l2[:]

>>> l1
[[1, 2, 3, 4, 5], [1, 2, 4, 6, 7]]
>>> l2
[[1, 2, 3, 6, 8], [1, 2, 3, 0, 9], [1, 2, 6, 7, 6]]
>>> l3
[[1, 2, 3, 6, 8], [1, 2, 3, 0, 9], [1, 2, 6, 7, 6]]

Upvotes: 0

pylang
pylang

Reputation: 44485

If order and types are not crucial, use sets instead. They are fast and resemble your examples:

set1 = {tuple(l) for l in l1}
set2 = {tuple(l) for l in l2}
set2 - set1
# {(1, 2, 3, 0, 9), (1, 2, 3, 6, 8), (1, 2, 6, 7, 6)}

The first two lines convert the lists into (unordered) sets of tuples, e.g.

{(1, 2, 4, 6, 7), (1, 2, 3, 4, 5)}
{(1, 2, 4, 6, 7), (1, 2, 3, 4, 5), (1, 2, 3, 0, 9), (1, 2, 3, 6, 8), (1, 2, 6, 7, 6)}

These forms allow set operations, i.e. one equivalent to the difference between set2 and set1.

Upvotes: 0

coder3521
coder3521

Reputation: 2646

Using Itertool :

import itertools
k = l2+l1
k = sorted(k)
list(k for k,_ in itertools.groupby(k))

itertools offers the fastest and most powerful solutions to this kind of problems , and will be efficient in terms of time , when the list size grows ,

And it's the pythonic way to achieve the solution , as the saying goes "When you are in Rome, Do like Romans."

Upvotes: 0

Ahmad
Ahmad

Reputation: 910

Use below code:

l1 = [[1,2,3,4,5], [1,2,4,6,7]]
l2 = [[1,2,3,4,5], [1,2,4,6,7], [1,2,3,6,8], [1,2,3,0,9], [1,2,6,7,6]]

l3=[]

for i in l2:
    if i not in l1:
        l3.append(i)

Upvotes: 0

timgeb
timgeb

Reputation: 78690

Build a set of tuples for the O(1) membership test. (In your trivial example, that would not be necessary, but I am assuming big lists.) Then filter via list comprehension.

>>> checker = set(map(tuple, l1))
>>> [l for l in l2 if tuple(l) not in checker]
[[1, 2, 3, 6, 8], [1, 2, 3, 0, 9], [1, 2, 6, 7, 6]]

Upvotes: 1

javidcf
javidcf

Reputation: 59701

Just do:

l3 = [lst for lst in l2 if lst not in l1]

Upvotes: 1

Related Questions