Python – how to remove a tuple from a list

Removing one or more tuple values ​​from a list in Python.

We have list of tuples:

[(1598900760, 0),
(1598900820, 9052),
(1598900880, 4866),
(1598900940, 3742),
(1598901240, None),
(1598901297, 0)]

Let’s remove everything from here that is zero or None.

for price in prices:
if price[1] == 0:
prices.remove(price)

for price in prices:
if price[1] is None:
prices.remove(price)

We get

[(1598900820, 9052),
(1598900880, 4866),
(1598900940, 3742)]

It would seem that it can be combined into one loop:

for price in prices:
if price[1] == 0 or price[1] is None:
prices.remove(price)

But no, in this case there will be something like (the last value was not removed):

[(1598900820, 9052),
(1598900880, 4866),
(1598900940, 3742),
(1598901297, 0)]

Apparently this is due to the peculiarity of creating objects in python.

Similar Posts

Leave a Reply