Reputation: 9378
(Python 2.7, Windows)
hello all, I have a list containing tuples and I want to filter out the "(0,0,35)":
a_list = [(0,0,35), (0,0,35), (9,12,12), (0,0,35), (5,12,6)]
for element in a_list:
if element is not "(0,0,35)":
print element
it does't work.
Can you show me the right way? thanks.
Upvotes: 0
Views: 116
Reputation: 1408
This doesn't work because you are testing against the string "(0,0,35)"
which is not the same as the tuple (0,0, 35)
. This should work:
a_list = [(0,0,35), (0,0,35), (9,12,12), (0,0,35), (5,12,6)]
for element in a_list:
if element != (0,0,35):
print element
A better solution would probably be to construct the filtered list using a list comprehension:
a_list = [(0,0,35), (0,0,35), (9,12,12), (0,0,35), (5,12,6)]
filtered_list = [e for e in a_list if e != (0,0,35)]
Upvotes: 3
Reputation: 19771
this should work:
[ x for x in a_list if x != (0,0,35) ]
demo:
>>> (1,2,3) == '(1,2,3)'
False
>>> str((1,2,3)) == '(1,2,3)'
False
>>> (1,2,3) == (1,2,3)
True
even if you force it to str ti will result in false
Upvotes: 1
Reputation: 19284
This will not work, because tuples cannot be represented as strings.
>>> (0, 0, 35) == "(0, 0, 35)"
False
>>>
Also, use !=
instead of is not
because ==
tests for equality (the prefix !
tests for inequality), but is
tests for the id
being the same (the not
checks for the id
not being the same).
>>> x = (0, 0, 35)
>>> x is (0, 0, 35)
False
>>> x == (0, 0, 35)
True
>>> id(x)
4299863136
>>> id((0, 0, 35))
4299863216
>>>
Try this:
a_list = [(0,0,35), (0,0,35), (9,12,12), (0,0,35), (5,12,6)]
for element in a_list:
if element != (0,0,35):
print element
Upvotes: 2