Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: list comprehension, do f(x) if x exists?

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!

like image 774
AP257 Avatar asked Nov 23 '10 19:11

AP257


People also ask

How do you apply condition in list comprehension?

Conditional Logic You can add an if statement at the end of a list comprehension to return only items which satisfy a certain condition. For example, the code below returns only the numbers in the list that are greater than two. This code returns a list of heights greater than 160 cm.

Does list comprehension exist in Python?

List comprehensions are a syntactic form in Python allowing the programmer to loop over and transform an iterable in one line.

Can we use function in list comprehension?

Answer: You can use any expression inside the list comprehension, including functions and methods.


2 Answers

The "if" goes at the end"

row = [unicode(x.strip()) for x in row if x]
like image 168
Adam Vandenberg Avatar answered Sep 26 '22 22:09

Adam Vandenberg


So close.

row = [unicode(x.strip()) for x in row if x]
like image 40
Ignacio Vazquez-Abrams Avatar answered Sep 26 '22 22:09

Ignacio Vazquez-Abrams