The syntax a if b else c is a ternary operator in Python that evaluates to a if the condition b is true - otherwise, it evaluates to c. It can be used in comprehension statements:

>>> [a if a else 2 for a in [0,1,0,3]]
[2, 1, 2, 3]

So for your example,

table = ''.join(chr(index) if index in ords_to_keep else replace_with
                for index in xrange(15))
Answer from Amber on Stack Overflow
🌐
Medium
medium.com › @anwar.basha7070 › conditional-logic-made-simple-ternary-operator-in-python-list-comprehensions-45d98525cb55
“Conditional Logic Made Simple: Ternary Operator in Python List Comprehensions” | by Anwar Basha | Medium
August 18, 2025 - The ternary operator allows inline if-else inside list comprehensions. Use it when you need to transform items based on a condition. Use the if at the end of comprehension when you need to filter items out.
🌐
Finxter
blog.finxter.com › python-ternary-in-list-comprehension
Python Ternary in List Comprehension – Be on the Right Side of Change
The syntax for the ternary operator in Python is: value_if_true if condition else value_if_false. For example, you can use the ternary operator to assign a string "even" or "odd" depending on the remainder of a number when divided by 2: number = 5 result = "even" if number % 2 == 0 else "odd" ...
🌐
Bernardo Lago
bernardolago.com › posts › python_shortcuts_ternary_operators_list_comprehension_dict_comprehension
Ternary Operators, List Comprehension, and Dict Comprehension | Bernardo Lago
January 4, 2024 - Ternary Operator in Complex Conditions: For complex conditions, prefer traditional if-else statements for clarity. Maintainability: Prioritize code maintenance; if the constructs hinder understanding, choose explicit alternatives. List comprehensions offer a concise way to create lists in Python.
🌐
Martin Heinz
martinheinz.dev › blog › 80
Python List Comprehensions Are More Powerful Than You Might Think | Martin Heinz | Personal Website & Blog
September 5, 2022 - It's possible to build a nested conditional using "conditional expressions", or as it's generally called a ternary operator. It's not exactly a pretty solution, so you will have to decide whether the few saved lines are worth the nasty one-liner. Apart from using complex conditionals, it's ...
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python ternary conditional operator
Python Ternary Conditional Operator - Spark By {Examples}
May 31, 2024 - The Python ternary operator can be used within list comprehensions to filter and transform data, resulting in concise and expressive code that is optimized for performance.
Find elsewhere
🌐
The Python Coding Stack
thepythoncodingstack.com › p › conditional-expression-ternary-operator-list-com
If You Find if..else in List Comprehensions Confusing, Read This, Else…
March 16, 2024 - But there's only one ternary operator, the conditional expression: <first operand> if <second operand> else <third operand> ... The single expression required by the list comprehension description is the conditional expression (a ternary operator!)
🌐
Designcise
designcise.com › web › tutorial › how-to-use-if-else-in-a-python-list-comprehension
How to Use "if-else" in a Python List Comprehension? - Designcise
January 8, 2023 - Starting with Python 2.5+, you can use if-else (which is actually the ternary operator) in a Python list comprehension to add a conditional expression. You can use the if-else clause in a list comprehension to transform the items (to one value ...
Top answer
1 of 3
7

Your "practical example" is written as:

>>> strList = ['Ulis', 'Tolus', 'Utah', 'Ralf', 'Chair']
>>> sum(1 for el in strList if el.startswith('U'))
2

Your other example (if I understand correctly) is:

>>> list1 = [4, 6, 7, 3, 4, 5, 3, 4]
>>> list1.count(4)
3

(or just adapt the strList example, but nothing wrong with using builtin methods)

2 of 3
2

@Jon Clements gave you an excellent answer: how to solve the problem using Python idiom. If other Python programmers look at his code, they will understand it immediately. It's just the right way to do it using Python.

To answer your actual question: no, that does not work. The ternary operator has this form:

expr1 if condition else expr2

condition must be something that evaluates to a bool. The ternary expression picks one of expr1 and expr2 and that's it.

When I tried an expression like c += 1 if condition else 0 I was surprised it worked, and noted that in the first version of this answer. @TokenMacGuy pointed out that what was really happening was:

c += (1 if condition else 0)

So you can't ever do what you were trying to do, even if you put in a proper condition instead of some sort of loop. The above case would work, but something like this would fail:

c += 1 if condition else x += 2  # syntax error on x += 2

This is because Python does not consider an assignment statement to be an expression.

You can't make this common mistake:

if x = 3:  # syntax error!  Cannot put assignment statement here
    print("x: {}".format(x))

Here the programmer likely wanted x == 3 to test the value, but typed x = 3. Python protects from this mistake by not considering an assignment to be an expression.

You can't do it by mistake, and you can't do it on purpose either.

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()]
🌐
Pythonpedia
pythonpedia.com › en › tutorial › 5265 › list-comprehensions
List Comprehensions | Python Language Tutorial
Note that this is quite different from the ... if ... else ... conditional expression (sometimes known as a ternary expression) that you can use for the <expression> part of the list comprehension.
🌐
Python.org
discuss.python.org › python help
Any other more elegant way than list comprehension? - Python Help - Discussions on Python.org
November 23, 2023 - x = [1,-1,-1,1] color = ['red' if i == 1 else 'gree' for i in x] color ['red', 'green', 'green', 'red'] I feel list comprehension is a bit of ugly,any other more elegant way
🌐
Mooc
programming-22.mooc.fi › part-11 › 1-list-comprehensions
List comprehensions - Python Programming MOOC 2022
As we can use conditions in list comprehensions, the else branch is also available with list comprehensions. The general syntax of the conditional used with list comprehensions looks like this: ... We came across these single line conditionals, or ternary operators, already in part 7.
🌐
DevRescue
devrescue.com › home › blog › python
Python Ternary List Comprehension - DevRescue
January 13, 2024 - This list comprehension iterates through a predefined list of numbers: [-2, -1, 0, 1, 2]. For each number x in this list, it checks if x is greater than 0. If x is greater than 0, “positive” is added to the new list; if x is less than or ...
🌐
Mooc
programming-25.mooc.fi › part-11 › 1-list-comprehensions
List comprehensions - Python Programming MOOC 2025
As we can use conditions in list comprehensions, the else branch is also available with list comprehensions. The general syntax of the conditional used with list comprehensions looks like this: ... We came across these single line conditionals, or ternary operators, already in part 7.
🌐
Reddit
reddit.com › r/learnpython › list comprehensions - using if else with enumerate.
r/learnpython on Reddit: List Comprehensions - using if else with enumerate.
December 22, 2019 -

I am trying to get my head around the syntax for list comprehensions.

My code below returns a list with the positions of the letter 's' in the string variable.

string = 'This is a sentence'
search = 's'

# this returns a list with [3,6,10]
result = [i for i, ch in enumerate(string) if ch ==search)] 

result = [3, 6, 10]

If I wanted to return only the even positions, I would do:

result = [i for i, ch in enumerate(string) if ch ==search) and i%2==0] 

result = [6, 10]

I notice that if the conditional comes at the start, then it has to have an else statement. Is that right? Is this to force a value whereas the example above just returns a filtered result?

e.g.:

result = [i if i%2 == 0 else None for i, ch in enumerate(string) if ch ==search)] 

result = [None, 6, 10]

Am I understanding this correctly?

🌐
Programmersought
programmersought.com › article › 5658981285
Python ternary operator, list comprehension, generator expression - Programmer Sought
1. an iterator Iterable object: ... expressions can not only simplify the code, it is also a so-called"Ve... Ternary expression is a fixed format in programming....