Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiline list comprehension in python

Tags:

python

list

How I make multiline list comprehension in Python? Something like:

[
  x for x in a:
    if check(x):
      ....
      #something multiline here
      ....
    else: 
      ....
      #something multiline here
      ....
]

Of course I know that I can to something like:

def f(x):
  if check(x):
     ....
  else: 
     ....
 return x

map(a,f)

But I want it without additional functions.

Is it possible?

like image 206
Igor Chubin Avatar asked Jun 21 '12 08:06

Igor Chubin


2 Answers

My understanding is that you can not do it as you suggested.

It's far more readable when you name the function and use list comprehension or map function compared to what you have suggested

like image 124
pyfunc Avatar answered Oct 05 '22 00:10

pyfunc


You can't, in the way you're thinking; list comprehensions can only contain expressions, not statements.

like image 23
Ignacio Vazquez-Abrams Avatar answered Oct 04 '22 23:10

Ignacio Vazquez-Abrams