-1

I am attempting to remove a tuple from a list based on its contents. The example illustrates what I have attempted to do:

i=[(a,0),(b,''),(c,5)]

The goal is to remove the tuple with an empty value in the second space. The final list would look like this:

i=[(a,0),(c,5)]

I have attempted to achieve this using the code:

for p in i:
    if '' in p[1]:
        i.remove(p)

However, if I print i at this point the list has no changes done to it. Where might I be going wrong?

Adam N
  • 1
  • 2

2 Answers2

0

You didn't mention it, but you're most probably getting a TypeError: argument of type 'int' is not iterable exception, the problem is that '' in 5 makes no sense at all. You probably want to use if p[1] == '' instead.

Another problem is that you won't be able to correctly remove elements from a list while you're iterating it.

A possible solution is to use a list comprehension:

i = [p for p in i if p[1] != '']
Francisco
  • 10,918
  • 6
  • 34
  • 45
0

The second element of each member of the tuple are not iterable (at least for the first and the last tuples), so you cannot use "in" in that cases. The most likely is that your "if" statement is something like

if p[1] == '':

And last, if you correct the problems that I mentioned before, you cando something like that:

i = filter(lambda x: x[1] != '', [(a,0), (b,''), (c,5)]

That is a more pythonic way to do that

JoseLSegura
  • 3,830
  • 3
  • 20
  • 27
  • Using a lambda is definitely not more pythonic than a list comp, also reassigning the name is not the same as updating the original list if you have other references to it. filter would also not give you a list back using python3. – Padraic Cunningham Oct 15 '16 at 23:53
  • With "more pythonic" I was referring to the "for" approach from the op. List comp is a good idea, but I guess that Francisco Couzo and me wrote the answer at the same time. I will investigate about filter in Py3, I didn't know that the behaviour of that has changed! – JoseLSegura Oct 16 '16 at 00:03
  • 1
    The OP's approach is just completely wrong be, while skewed `"" in ""` would also actually be True as every string is said to contain an empty string. – Padraic Cunningham Oct 16 '16 at 00:07