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
  • 26,565
  • 10
  • 94
  • 165
AP257
  • 89,519
  • 86
  • 202
  • 261
  • 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

20

The "if" goes at the end"

row = [unicode(x.strip()) for x in row if x]
Adam Vandenberg
  • 19,991
  • 9
  • 54
  • 56
  • 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
  • 776,304
  • 153
  • 1,341
  • 1,358
3

Not sure about the goals, but this should work

row = [unicode(x.strip()) for x in row if x ]
pyfunc
  • 65,343
  • 15
  • 148
  • 136
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,818
  • 3
  • 43
  • 55