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.
🌐
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.
🌐
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" ...
🌐
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!)
🌐
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 also possible to stack multiple ifs in a comprehension:
🌐
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
🌐
Codevisionz
codevisionz.com › home › usage of the ternary operator for grade determination
Using Nested Ternary Operators and List Comprehensions
May 14, 2025 - The outermost ternary operator checks if score is greater than or equal to 90. ... This ensures that the appropriate grade is assigned based on the value of score. ... A list named scores is created, containing a series of integers representing different scores. grades = [determine_grade(score) for score in scores] ... List comprehensions provide a concise way to create lists.
🌐
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
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. Consider the following example: [x if x % 2 == 0 else None for x in range(10)] # Out: [0, None, 2, None, 4, None, 6, None, 8, None] ... Here the conditional expression isn't a filter, but rather an operator determining the value to be used for the list items:
🌐
AlgoMaster
algomaster.io › learn › python › ternary-operator
Ternary Operator | Python | AlgoMaster.io | AlgoMaster.io
In this list comprehension example, we double the values greater than 25, demonstrating how the ternary operator can streamline data processing. While the ternary operator is generally straightforward, there are some edge cases and nuances that can catch you off guard. Be cautious with type coercion when using the ternary operator. The expression evaluates to one of two types, and if they are different, Python ...
🌐
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 ...
🌐
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.
🌐
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.
🌐
Stack Overflow
stackoverflow.com › questions › 70312474 › is-this-ternary-operator-or-list-comprehension
python 3.x - Is this ternary operator or list comprehension - Stack Overflow
So above program is ternary operator or list comprehension? ... It is both. Given the expression ["even" if i%2==0 else "odd" for i in h] we have a ternary expression: ... Expressions can be composed together.