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.
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.
Note: You cannot remove items in a tuple.
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.
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.
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.
You can also do:
>>> OutputList = filter(ListTuples, lambda x: x[0] >= 50)
>>> OutputList
[(100, 'AAA'), (80, 'BBB')]
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.
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')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With