You don't need any conditional expression* here, as str.split() always returns a list, even if only containing one word:

lst[:] = [word for words in lst for word in words.split()]

Demo:

>>> lst = ['word','word','multiple words','word']
>>> [word for words in lst for word in words.split()]
['word', 'word', 'multiple', 'words', 'word']

The conditional expression can be used wherever you could use a simple expression in the syntax; that means anywhere it says expression or old_expression in the list display grammar:

list_display        ::=  "[" [expression_list | list_comprehension] "]"
list_comprehension  ::=  expression list_for
list_for            ::=  "for" target_list "in" old_expression_list [list_iter]
old_expression_list ::=  old_expression [("," old_expression)+ [","]]
old_expression      ::=  or_test | old_lambda_expr
list_iter           ::=  list_for | list_if
list_if             ::=  "if" old_expression [list_iter]

So the first part of a list comprehension, but also the part that produces the outermost iterator (evaluated once), the if expressions, or any of the nested iterators (evaluated each iteration of the next outer for loop).

*It's called the conditional expression; it is a ternary operator, but so is the SQL BETWEEN operator.

Answer from Martijn Pieters on Stack Overflow
Top answer
1 of 2
3

You don't need any conditional expression* here, as str.split() always returns a list, even if only containing one word:

lst[:] = [word for words in lst for word in words.split()]

Demo:

>>> lst = ['word','word','multiple words','word']
>>> [word for words in lst for word in words.split()]
['word', 'word', 'multiple', 'words', 'word']

The conditional expression can be used wherever you could use a simple expression in the syntax; that means anywhere it says expression or old_expression in the list display grammar:

list_display        ::=  "[" [expression_list | list_comprehension] "]"
list_comprehension  ::=  expression list_for
list_for            ::=  "for" target_list "in" old_expression_list [list_iter]
old_expression_list ::=  old_expression [("," old_expression)+ [","]]
old_expression      ::=  or_test | old_lambda_expr
list_iter           ::=  list_for | list_if
list_if             ::=  "if" old_expression [list_iter]

So the first part of a list comprehension, but also the part that produces the outermost iterator (evaluated once), the if expressions, or any of the nested iterators (evaluated each iteration of the next outer for loop).

*It's called the conditional expression; it is a ternary operator, but so is the SQL BETWEEN operator.

2 of 2
3

First of all, you have the order wrong. To use the ternary operator, you have to do it like this:

[a if c else b for item in list]

That being said, you cannot really have another list comprehension level embedded depending on some condition. The number of levels has to be fixed.

As you are just looking to split for whitespace, you can just perform this anyway though, as splitting a string without whitespace will still give you back a list with a single item back:

[subword for word in list for subword in word.split()]
🌐
GeeksforGeeks
geeksforgeeks.org › python › ternary-operator-in-python
Ternary Operator in Python - GeeksforGeeks
Lambdas can be used in conjunction with the ternary operator for inline conditional logic. ... Explanation: This defines an anonymous function (lambda) that takes two arguments and returns the larger one using the ternary operator. It is then called with a and b. The ternary operator can also be directly used with the Python print statement.
Published   December 20, 2025
🌐
Penn State University
e-education.psu.edu › ngapython › node › 636
Loops, if/else, ternary operators | NGA Advanced Python Programming for GIS, GLGI 3001-1
Therefore, they should only be ... of for /while and if-else would do. Lesson content developed by Jan Wallgrun and James O’Brien · ‹ Class attributes and static class functions up Expressions, if/else & ternary operator, and match › · NGA Advanced Python Programming ...
🌐
Finxter
blog.finxter.com › home › learn python blog › python ternary for loop: simplifying conditional expressions in iterations
Python Ternary For Loop: Simplifying Conditional Expressions in Iterations - Be on the Right Side of Change
December 4, 2023 - ... In this case, the result variable will be assigned the value "Even" if x is divisible by 2 and "Odd" otherwise. A ternary for loop in Python combines the concepts of the ternary operator and for loop to create a compact looping structure.
🌐
Mimo
mimo.org › glossary › python › ternary-operator
Python Ternary Operator: Syntax, Usage, and Examples
It's a One-Line if-else: Its main purpose is to replace a simple if-else block that assigns a value to a variable. Unique Syntax: Remember the Python-specific structure: value_if_true if condition else value_if_false. Improves Readability for Simple Cases: ...
🌐
DataFlair
data-flair.training › blogs › python-ternary-operator
Python Ternary Operator - 5 Ways To Implement Ternary Operators - DataFlair
July 14, 2025 - Python Ternary Operator Tutorial with syntax and examples, what are Ternary Operator in Python,Python Ternary without else, Python If else
🌐
Python Tutorial
pythontutorial.net › home › python basics › python ternary operator
Python Ternary Operator
March 26, 2025 - In this tutorial, you'll learn about the Python ternary operator and how to use it to make your code more concise.
🌐
O'Reilly
oreilly.com › library › view › python-cookbook › 0596001673 › ch17s06.html
Simulating the Ternary Operator in Python - Python Cookbook [Book]
There are many ways to skin a ternary operator. An explicit if/else is most Pythonic, but somewhat verbose: for i in range(1, 3): if i == 1: plural = '' else: plural = 's' print "The loop ran %d time%s" % (i, plural)
Find elsewhere
🌐
FavTutor
favtutor.com › blogs › ternary-operator-python
Python Ternary Operator With Examples | FavTutor
Just for this reason, Python makes use of conditional statements and loops to avoid writing the same program and executing the same block of code over and over again until the condition is true. The ternary operator is one such shorter way of writing the conditional statement in Python.
Top answer
1 of 5
28

1 if A else 2 if B else 3 translates to this:

def myexpr(A, B):
    if A:
        return 1
    else:
        if B:
            return 2
        else:
            return 3

Your ternary expression can be interpreted with parentheses as follows:

(
 (1 if A) else (
                (2 if B) else 3
               )
)
2 of 5
7

Could someone please explain why this is executed in this order, and possibly suggest some material that gives an intuition about why this is used/preferred?

I'm trying to answer the "intuition" part of your question by solving a simple but more general problem.

'''
+-----------------------------------------------------------------------------------+
|                                    Problem:                                       |
+-----------------------------------------------------------------------------------+
| Convert a                                                                         |
| nested if-else block into                                                         |
| a single line of code by using Pythons ternary expression.                        |
| In simple terms convert:                                                          |
|                                                                                   |
|      1.f_nested_if_else(*args) (  which uses                                      |
|      ````````````````````        nested if-else's)                                |
|            |                                                                      |
|            +--->to its equivalent---+                                             |
|                                     |                                             |
|                                     V                                             |
|                              2.f_nested_ternary(*args) (     which uses           |
|                              ```````````````````       nested ternary expression) |
+-----------------------------------------------------------------------------------+
'''
'''
Note:
C:Conditions  (C, C1, C2)
E:Expressions (E11, E12, E21, E22)
Let all Conditions, Expressions be some mathematical function of args passed to the function
'''    

#-----------------------------------------------------------------------------------+
#| 1. |      Using nested if-else                                                   |
#-----------------------------------------------------------------------------------+
def f_nested_if_else(*args):
    if(C):
        if(C1):
            return E11
        else:
            return E12
    else:
        if(C2):
            return E21
        else:
            return E22

#-----------------------------------------------------------------------------------+
#| 2. |      Using nested ternary expression                                        |
#-----------------------------------------------------------------------------------+
def f_nested_ternary(*args):
    return ( (E11) if(C1)else (E12) )   if(C)else   ( (E21) if(C2)else (E22) )


#-----------------------------------------------------------------------------------+
#-----------------------------------------------------------------------------------|
#-----------------------------------------------------------------------------------|
#-----------------------------------------------------------------------------------|
#-----------------------------------------------------------------------------------+

Here is a visualization of why f_nested_if_else() and f_nested_ternary() are equivalent.

#     +-----------------------------------------------------------------------------+
#     |                               Visualization:                                |
#     +-----------------------------------------------------------------------------+
#     |         Visualize the ternary expression like a binary tree :               |
#     |           -Starting from the root and  moving down to the leaves.           |
#     |           -All the internal nodes being conditions.                         |
#     |           -All the leaves being expressions.                                |
#     +-----------------------------------------------------------------------------+
                                     _________________
                                     |f_nested_ternary|                                 
                                     ``````````````````
            ( (E11) if(C1)else (E12) )   if(C)else   ( (E21) if(C2)else (E22) )
                |       |        |          |            |       |        |
                |       |        |          |            |       |        |
                V       V        V          V            V       V        V                                                                             
Level-1|                  +----------------(C)-----------------+         
--------             True/          __________________           \False         
                        V           |f_nested_if_else|            V              
Level-2|          +----(C1)----+    ``````````````````     +----(C2)----+     
--------     True/              \False                True/              \False
                V                V                       V                V     
Level-3|    ( (E11)            (E12) )               ( (E21)            (E22) ) 
------------------------------------------------------------------------------------+

Hope this visualization gave you an intuition of how nested ternary expressions are evaluated :P

🌐
DataCamp
datacamp.com › tutorial › pythons-ternary-operators-guide
Python's Ternary Operators Guide: Boosting Code Efficiency | DataCamp
May 17, 2024 - When combined with tuples, immutable sequences of elements, ternary operators allow for compact and readable conditional expressions. In the context of tuples, the ternary operator selects one of two values based on a condition and returns it. This is achieved by indexing the tuple using the result of the condition as the index. If the condition is True, in Python True =1, the element at index 1 (corresponding to result_if_true) is returned; otherwise, the element at index 0 (corresponding to result_if_false) is returned.
🌐
Python Examples
pythonexamples.org › python-ternary-operator
Python Ternary Operator
This example demonstrates that you can run any Python function inside a Ternary Operator. You can nest a ternary operator in another statement with ternary operator. In the following example, we shall use nested ternary operator and find the maximum of three numbers. a, b, c = 15, 93, 22 #nested ternary operator max = a if a > b and a>c else b if b>c else c print(max) After the first else keyword, that is another ternary operator. ... Change the values for a, b and c, and try running the nested ternary operator.
🌐
Educative
educative.io › answers › what-is-the-ternary-operator-in-python
What is the ternary operator in Python?
Let’s write a Python code snippet to check if an integer is even or odd. ... The above code is using the ternary operator to find if a number is even or odd. msg will be assigned “even” if the condition (to_check % 2 == 0) is true. msg will be assigned “odd” if the condition (to_check % 2 == 0) is false. Note: Every code using the if-else statement cannot be replaced with the ternary operator. For ...
🌐
Sentry
sentry.io › sentry answers › python › does python have a ternary conditional operator?
Does Python Have a Ternary Conditional Operator? | Sentry
If so, what is the structure of a Python ternary operator? The ternary operator is used to shorten the code needed to write if-else blocks. The syntax of ternary operators naturally differs between languages, but in most cases, the operator ...
🌐
Stack Overflow
stackoverflow.com › questions › 41511734 › ternary-operator-in-enumeration-loop
python - Ternary operator in enumeration loop - Stack Overflow
A ternary operator takes 3 operands (it's in the name). Yours only has 2, so no, that won't work. ... Python suffers a bit from keyword overload here. if can used to start a conditional statement (if ... then ... elif ... else), in a conditional ...
🌐
W3Schools
w3schools.com › python › python_if_shorthand.asp
Python Shorthand If
If you have one statement for if and one for else, you can put them on the same line using a conditional expression: ... This is called a conditional expression (sometimes known as a "ternary operator").
🌐
Dataquest
dataquest.io › blog › python-ternary-operator
Python Ternary: How to Use It and Why It's Useful (with Examples)
March 6, 2023 - The ternary operator was introduced in Python 2.5. The syntax consists of three operands, hence the name "ternary": ... While the ternary operator is a way of re-writing a classic if-else block, in a certain sense, it behaves like a function since it returns a value. Indeed, we can assign the result of this operation to a variable: ... Before we had the ternary operator, instead of a if condition else b, we would use condition and a or b. For example, instead of running the following .
Top answer
1 of 2
2

You have to use a generator expression for that:

return next((x2 for x, x2 in opts if x == "--config"), str())

The expression (x2 for x, x2 in opts if x == 1) is a generator: it can be used to iterate over a set of elements. For instance:

opts = [(1, 2), (1, 3), (2, 4)]
gen = (x2 for x, x2 in opts if x == 1)
for x in gen:
  print(x)  #  print 2 and 3

next returns the next element of the generator (or the first if you have not generated any element for now).

If the generator does not contain any next element, then the second (optional) argument of next is returned. Otherwise an exception is raised. For instance:

opts = [(1, 2), (2, 3)]

gen = (x2 for x, x2 in opts if x == 4)
x = next(gen)  #  raise StopIteration

gen = (x2 for x, x2 in opts if x == 4)
x = next(gen, 5)
print(x)  # print 5

So to summarise, return next((x2 for x, x2 in opts if x == "--config"), str()) is equivalent to your for loop: using your generator you take the first element x, x2 of opts such that x == "--config" and return x2 ; and if there is no such element you return str()

2 of 2
1

There are a few pieces to this.

The fallback return of str() will always give '' as you are asking it for the string value of literally nothing. If that's what you want you might as well return '' instead.

Unless all of your opts are 2-tuples (or other iterables with 2 elements each), then anything singleton opt will fail at for x, x2 in opts. At a guess, you are more likely feeding a list of strings to this function, examples being

opt_config(['--config', 'elderberries', 'castle']) -> 'elderberries'
opt_config(['grail', 'swallow', '--config', 'rabbit']) -> 'rabbit'
opt_config(['parrot', 'cheese', 'Olympics']) -> ''

Again, speculating on what you want, it appears you want either the first config option given (and only the first), or '' if '--config' never shows up.

If my interpretations of your intentions are correct, then something like this might be what you want for the 'non-ternary' version of the code:

def opt_config(opts):
    if '--config' in opts:
        ndx = opts.index('--config')
        if ndx < len(opts):
            return opts[ndx + 1]
    return ''

opt_config(['--config', 'elderberries', 'castle'])
'elderberries'

opt_config(['grail', 'swallow', '--config', 'rabbit'])
'rabbit'

opt_config(['parrot', 'cheese', 'Olympics'])
''

If you want to compress that code down you can take it all the way to a 1-liner using the ternary operator you asked about:

opt_config2 = lambda opts: opts[opts.index('--config') + 1] if '--config' in opts[:-1] else ''

opt_config2(['--config', 'elderberries', 'castle'])
'elderberries'

opt_config2(['grail', 'swallow', '--config', 'rabbit'])
'rabbit'

opt_config2(['parrot', 'cheese', 'Olympics'])
''

With the ternary operator x if y else z, the if y part is evaluated first, so python efficiently calculates only one of the x and z options as required.