13

How can I do something like the following in Python?

row = [unicode(x.strip()) if x for x in row]

Basically, a list comprehension where you carry out a function if the variable exists.

Thanks!

hlovdal
  • 24,540
  • 10
  • 85
  • 154
AP257
  • 81,509
  • 84
  • 194
  • 260
  • You say, if the variable exists, but I think you mean, if it is not None. The "for x in row" bit will walk through all of the "variables" in row. – Aaron H. Nov 23 '10 at 19:21
  • 3
    Also, if you want to check for `None`, use `x is not None`. –  Nov 23 '10 at 19:27
  • 1
    I think this question very similar to http://stackoverflow.com/questions/4260280/python-if-else-in-list-comprehension should not re-post the same question twice – anijhaw Nov 23 '10 at 21:58

4 Answers4

19

The "if" goes at the end"

row = [unicode(x.strip()) for x in row if x]
Adam Vandenberg
  • 18,893
  • 7
  • 52
  • 55
  • Perfect, thank you. As @delnan comments above, what I really need is 'x is not None' - though that's my fault for an ambiguous explanation. – AP257 Nov 23 '10 at 19:37
3

So close.

row = [unicode(x.strip()) for x in row if x]
Ignacio Vazquez-Abrams
  • 740,318
  • 145
  • 1,296
  • 1,325
3

Not sure about the goals, but this should work

row = [unicode(x.strip()) for x in row if x ]
pyfunc
  • 63,167
  • 15
  • 145
  • 135
1

Maybe you're were thinking of the ternary operator syntax as used if you want if/else, e.g.:

row = [unicode(x.strip()) if x is not None else '' for x in row ]

or whatever you'd want to do.

Morten Jensen
  • 5,555
  • 3
  • 41
  • 54