11

I've knocking my head against a wall with this:

Basically what I want is to remove " " items from this list of tuples:

[('650', '724', '6354', '', '', ''), ('', '', '', '650', '723', '4539')]

and obtain the following new list:

[('650', '724', '6354'), ('650', '723', '4539')]

any ideas?

Altons
  • 1,422
  • 3
  • 12
  • 23

2 Answers2

26

Tuples in Python are immutable. This means that once you have created a tuple, you can't change the elements contained within it. However, you can create a new tuple that doesn't contain the items you don't want. For example:

>>> a = [('650', '724', '6354', '', '', ''), ('', '', '', '650', '723', '4539')]
>>> [tuple(y for y in x if y) for x in a]
[('650', '724', '6354'), ('650', '723', '4539')]

This uses a list comprehension [... for x in a] to create a new list using the formula in .... That uses a generator expression y for y in x if y to create a new tuple containing the elements of x only if y is true (meaning the value is truthy, or the string is nonblank).

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
0
a = [('650', '724', '6354', '', '', ''), ('', '', '', '650', '723', '4539')]

print [tuple(x for x in y if x) for y in a]
PasteBT
  • 2,128
  • 16
  • 17