miik
miik

Reputation: 663

Removing items from a list in python

I am new to python and I'm wondering, how I would go about removing items from a list. Say I have the list:

a=[(102,12,0),(123,12,0),(124,12,1)]

I would like to remove the items that have a 0 at the end, so my list would end up like:

a = [(124,12,1)]

Upvotes: 3

Views: 1075

Answers (3)

Ketouem
Ketouem

Reputation: 3857

Not as awesome as a one liner list comprehension but still do the trick :).

b = tuple
for tple in a:
    b = b + tple
result = tuple
for val in set(b):
    if val % 10 != 0:
        result = result + (val,)

Upvotes: 1

Inbar Rose
Inbar Rose

Reputation: 43437

here:

a = [i for i in a if i[-1] != 0] #list comprehension (1 line) method.

"normal" way to do without list comprehension when the parent list is also destination list.

tmp = []
for i in a:
    if i[-1] != 0:
        tmp.append(i)
a = tmp

in action:

>>> a=[(102,12,0),(123,12,0),(124,12,1)]
>>> a = [i for i in a if i[-1] != 0]
>>> a
[(124, 12, 1)]
>>> 

Upvotes: 6

karthikr
karthikr

Reputation: 99620

You can use list comprehensions

val[-1] would give you tuples with 0 at the end, assuming val is the variable used while iterating.

So, your code would be something like this:

a = [val for val in a if val[-1]]

Upvotes: 2

Related Questions