1

Is there a way to write something like this in one line?

for x in list: 
   if condition1: 
       (...) 
   elif condition2: 
       (...) 
   else: 
       (...) 

Another way of asking is: Is it possible to combine following list comprehensions?

(...) for x in list

and

123 if condition1 else 345 if condition2 else 0
finefoot
  • 9,914
  • 7
  • 59
  • 102
kuku
  • 109
  • 1
  • 6

4 Answers4

2

What you want to do would almost certainly be considered bad style. Maybe it's an XY problem? In that case, you should open another question with the underlying issue.

If you're sure this is what you want, have a look at the following example, using PEP 308 -- Conditional Expressions :

>>> def f(condition1, condition2):
...     return 1 if condition1 else 2 if condition2 else 3
... 
>>> f(True, False)
1
>>> f(True, True)
1
>>> f(False, True)
2
>>> f(False, False)
3

Subsequently, your example

for x in list: 
   if condition1: 
       (...) 
   elif condition2: 
       (...) 
   else: 
       (...) 

could be written as a list comprehension as follows:

[(...) if condition1 else (...) if condition2 else (...) for x in list]
finefoot
  • 9,914
  • 7
  • 59
  • 102
0

use lsit comprehensions

var = [i for i in list if i == something or i == something] more on that here

nexla
  • 434
  • 7
  • 20
0

Yes, there are ways, but not recommended. Here is an example of how you could do it:

l = [1,2,3,4,5,6,7]

for x in l:
  if x%2 == 0:
    print("Even")
  elif x%2 == 1:
    print("Odd")
  else:
    print("Nothing")

print("And here the one-liner:")

[print("Even") if x%2 == 0 else print("Odd") if x%2 == 1 else print("Nothing") for x in l]

I don't recommend this way, because of readability. Read The Zen of Python, don't make too long lines (max 80 characters)

ZAIMON__
  • 1
  • 5
0

The way to write for loop in a single line, mostly used in Data Science Project, You can use this way, as we have six labeled fake news LIAR:

Labels: ['barely-true' 'false' 'half-true' 'mostly-true' 'pants-fire' 'true'], to represent this as a binary labels:

We use the following way:

labels = [ 1 if lab=='false' or lab=='pants-fire' or lab=='barely_true'  else 0 for lab in df.is_fake]

Another way, the same if-else condition for loop:

labels = [ 1 if lab=='false' else 1 if lab=='pants-fire' else 1 if lab=='barely_true'  else 0 if lab == 'true' else 0 if lab == 'half-true' else 0 for lab in df.is_rumor]

Hope to help many of you, who want to do the same way in many problem-solving.