Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove tuple from list of tuples if certain condition is met

I have a list of tuples that look like this;

ListTuples = [(100, 'AAA'), (80, 'BBB'), (20, 'CCC'), (40, 'DDD')]

I want to remove the tuples when the first element of the tuple is less than 50. The OutputList will look like this;

OutputList = [(100, 'AAA'), (80, 'BBB')]

How can this be done in python?

Thank you very much for your help.

like image 539
guagay_wk Avatar asked Apr 09 '14 09:04

guagay_wk


People also ask

How do I remove a specific tuple from a list?

Use the del statement to remove a tuple from a list of tuples, e.g. del list_of_tuples[0] . The del statement can be used to remove a tuple from a list by its index, and can also be used to remove slices from a list of tuples.

Can you use Remove with tuple?

Note: You cannot remove items in a tuple.

Can we remove individual tuple elements?

Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting together another tuple with the undesired elements discarded. To explicitly remove an entire tuple, just use the del statement.

Can we modify tuple of list in Python?

Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called. But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.


Video Answer


4 Answers

You can easily do it as:

out_tup = [i for i in in_tup if i[0] >= 50]

[Out]: [(100, 'AAA'), (80, 'BBB')]

This simply creates a new list of tuples with only those tuples whose first element is greater than or equal to 50. Same result, however the approach is different. Instead of removing invalid tuples you accept the valid ones.

like image 66
sshashank124 Avatar answered Oct 22 '22 08:10

sshashank124


You can also do:

>>> OutputList = filter(ListTuples, lambda x: x[0] >= 50)
>>> OutputList
[(100, 'AAA'), (80, 'BBB')]
like image 37
anon582847382 Avatar answered Oct 22 '22 10:10

anon582847382


Code snippet for timing the solutions given by sshashank124 and Alex Thornton:

ListTuples = [(100, 'AAA'), (80, 'BBB'), (20, 'CCC'), (40, 'DDD')]
import timeit
timeit.timeit('[i for i in ListTuples if i[0] >= 50]', globals=globals(), number=1000000)
>>> 0.6041104920150246

timeit.timeit('filter(lambda x: x[0] >= 50, ListTuples)', globals=globals(), number=1000000)
>>> 0.3009479799948167

The build-in filter() solution is faster for this example.

like image 4
Peter Smit Avatar answered Oct 22 '22 09:10

Peter Smit


We can Do this with simple counter and a new list:

   new = []

   for i in ListTuples:
        for j in i:
            if ( counter % 2 == 0 ):
                if ( j > 50):
                    new.append(i)
            counter = counter +1

output :

[(100, 'AAA') , (80, 'BBB')]
like image 2
keyvan vafaee Avatar answered Oct 22 '22 09:10

keyvan vafaee