Rajat Gupta
Rajat Gupta

Reputation: 1959

How to delete elements from list of tuples?

I want to delete the list of tuple in python. I have the list

l = [('name','sam'),('age', 20),('sex', 'male')]

and another list of tuples

r = [('name','sam'),('age', 20)]

I am trying to delete those elements which are in r and l both. I am doing this:

for item in l:
   if item in r:
       del item

But the elements are not deleting. The output is nothing and when I print the modified list:

>>> l

Then original list is printing.

[('name','sam'),('age', 20),('sex', 'male')]

Please help me, how can I delete elements from list of tuples.

Upvotes: 3

Views: 326

Answers (4)

Shivam Gupta
Shivam Gupta

Reputation: 82

There are many approaches to go screw this problem:

  1. find AND of those list by l and r for finding which are common in both then use to manipulate this in such a way: [x for x in l if x not in l and r ]. this will be little more efficient than above answers.

  2. Correct marked answer will fall in some cases like what if len(l) < len(r). so for overcome this problem simply list=[] p = l and r list.extend([ [x for x in l if x not in p ], [x for x in r if x not in p ]]) Hope it will fade out some uncovers.

Upvotes: 0

kdani
kdani

Reputation: 847

You can use a filter().

for item in filter(lambda x: x not in r, l):
    # You can use your items here

# The list gets out of scope, so if there are no other references,
# the garbage collector will destroy it anyway

Or, if you need to use the list elsewhere too, you might also consider creating a new list instead, using a list comprehension:

l = [i for i in l if i not in r]

Upvotes: 0

zazga
zazga

Reputation: 366

This will return a list of items that are in l and not in r.

The difference between this solution and the solution to substract sets is that you do not lose information if you have duplicates inside your list. You lose this information with substracting sets

difference = [item for item in l if item not in r]

Upvotes: 0

Bonifacio2
Bonifacio2

Reputation: 3840

You can tranform both lists in sets and subtract them:

l = [('name','sam'),('age', 20),('sex', 'male')]
r = [('name','sam'),('age', 20)]

The following line will return only the elements that are in l but aren't in r:

set(l) - set(r)

Upvotes: 3

Related Questions