You are producing a filtered list by using a list comprehension. i is still being bound to each and every element of that list, and the last element is still 'three', even if it was subsequently filtered out from the list being produced.

You should not use a list comprehension to pick out one element. Just use a for loop, and break to end it:

for elem in my_list:
    if elem == 'two':
        break

If you must have a one-liner (which would be counter to Python's philosophy, where readability matters), use the next() function and a generator expression:

i = next((elem for elem in my_list if elem == 'two'), None)

which will set i to None if there is no such matching element.

The above is not that useful a filter; your are essentially testing if the value 'two' is in the list. You can use in for that:

elem = 'two' if 'two' in my_list else None
Answer from Martijn Pieters on Stack Overflow
🌐
Sololearn
sololearn.com › en › Discuss › 2336541 › solved-how-to-use-for-loop-and-if-statement-in-one-line
[solved] How to use for loop and if statement in one line??
Sololearn is the world's largest community of people learning to code. With over 25 programming courses, choose from thousands of topics to learn how to code, brush up your programming knowledge, upskill your technical ability, or stay informed about the latest trends.
Discussions

A "for ... if" statement - Ideas - Discussions on Python.org
What do people think about a simple (in theory?) addition to the for loop to make the following valid Python: for val in iterator if predicate(val): # do stuff with val This would be equivalent to for val in iterator: if predicate(val): # do stuff with val The closest you can get currently ... More on discuss.python.org
🌐 discuss.python.org
2
April 14, 2022
If-else condition in one liner
for x in lst: _prev = x if x else prev What could why do you need x to be overwritten before it’s next loop…can now just use prev for the rest of the code block. x, _prev = (x,x) if x else (_prev, _prev) This should illuminate though why it’s seem pretty ridiculous to need. And give you a direct answer yes we can do this if we really wanted. But x won’t change the list, to do that we should….just make a new list. new_replace = [] _prev = None for x in my_list: _prev = x if x else _prev #do_something(_prev) new_replace.append(_prev) We can one line this…well two line technically, maybe if the first value is never empty we can omit, not sure. _prev = None _replace = [(_prev := x if x else _prev) for x in my_list] Pretty straightforward use of the walrus operation. (All we are doing is assigning and returning at the same time.) At this point you can just throw walrus into whatever function itself. And get right to it. And forget about it lists and stuff. _prev = None for x in my_list: no_empty_function(_prev := x if x else _prev) This is actually a fairly fast progression of a concept. And IMHO significantly “one lined”. (Though we can go further.) Or some enumerate() stuff but it honestly screams walrus function. I don’t need to make indexes and reference them, I already used the last value I just use it again. All that referencing get troublesome with huge datasets. Now my_list can be my_generator. More on reddit.com
🌐 r/learnpython
29
1
August 21, 2023
How can I write this for loop in one line?
The loop itself is perfectly fine. One small optimization you could do is with your if/else statement however; for i, day in enumerate(week): week_fmt.append(day) if i < 5: # Duplicate first 5 days week_fmt.append(day) Could you turn this into a one-liner? Probably. Should you want to? Absolutely not. You'd just make things more complicated than they need to be, and maybe more importantly, no one will be able to understand what you wrote. As a side note, I am kinda curious what the purpose of this week_fmt list is. I have a feeling that what you're doing can be achieved more easily. If you want, briefly explain what this loop is for, and we may still be able to make a clean one-liner after all. More on reddit.com
🌐 r/learnpython
11
8
January 1, 2024
python - Single line for loop over iterator with an "if" filter? - Stack Overflow
I have a simple for loop followed by a simple if statement: for airport in airports: if airport.is_important: and I was wondering if I can write this as a single line somehow. Yes, I can do th... More on stackoverflow.com
🌐 stackoverflow.com
People also ask

What is the syntax for a one-line if else in Python?
Use a conditional expression: value_if_true if condition else value_if_false; only the chosen branch is evaluated.
🌐
golinuxcloud.com
golinuxcloud.com › home › programming › python one line if else
How to use python if else in one line with examples
Can I write true elif on a single line?
There is no elif token inside an expression; you chain conditional expressions instead, which is not the same control-flow structure as a multi-line if/elif/else.
🌐
golinuxcloud.com
golinuxcloud.com › home › programming › python one line if else
How to use python if else in one line with examples
Is a list comprehension the same as a for loop?
It is syntactic sugar for a common for-loop pattern that builds a list; the interpreter still loops, but the intent is visible in one expression.
🌐
golinuxcloud.com
golinuxcloud.com › home › programming › python › python for loop in one line
Python for Loop in One Line: List Comprehension, if, else, and ...
🌐
GoLinuxCloud
golinuxcloud.com › home › programming › python › python for loop in one line
Python for Loop in One Line: List Comprehension, if, else, and Examples
January 9, 2024 - Putting heavy I/O or database work ... The idiomatic “one-line for” in Python is usually a list, dict, or set comprehension, or a generator expression when you want laziness....
🌐
Treehouse Blog
blog.teamtreehouse.com › python-single-line-loops
Simplify Your Python Loops with Comprehensions [Tutorial] | Treehouse Blog
May 13, 2026 - A list comprehension is a concise way to create lists in Python. It uses a single line of code to iterate over an iterable, apply an expression to each item, and optionally filter elements using conditions. Example: ... Use a list comprehension when the operation is simple and can be clearly expressed in one line. For complex logic or multiple nested conditions, traditional loops may be more readable and maintainable.
🌐
Finxter
blog.finxter.com › home › learn python blog › python one line for loop with if
Python One Line For Loop With If - Be on the Right Side of Change
July 20, 2020 - Again, you can use list comprehension [i**2 for i in range(10) if i%2==0] with a restrictive if clause (in bold) in the context part to compress this in a single line of Python code: print([i**2 for i in range(10) if i%2==0]) # [0, 4, 16, 36, 64] This line accomplishes the same output with much less bits. Related Article: Python One Line For Loop ·
🌐
Script Everything
scripteverything.com › posts › inline for loop with if statements (code examples)
Inline For Loop With If Statements (Code Examples) | Script Everything
December 2, 2021 - As you can see from the output above the Python REPL shows it is expecting something more at the end of the one line for loop (being the colon) and therefore reports an error of invalid syntax. Another handy feature of the one-liner for loop is that it also permits the use of conditions both before and after the for loop section. Each if statement placed has its own particulars on what happens to each element in the for loop.
Find elsewhere
🌐
YouTube
youtube.com › watch
'For' loops and 'If' conditions in one line - YouTube
This is a Tips and Tricks video for advanced coding in python."How to convert multiple 'For' loops and 'if' conditions into one line."leave a comment to ask ...
Published   March 4, 2023
🌐
Finxter
blog.finxter.com › can-i-write-a-for-loop-and-if-statement-in-a-single-line-a-simple-python-tutorial
Can I Write a For Loop and If Statement in a Single Line? A Simple Python Tutorial – Be on the Right Side of Change
💡 Example: If you have colors = ["red", "blue", "green"] and you want to filter out only “blue”, a list comprehension like [color for color in colors if color == "blue"] would return ['blue']. However, the variable color will hold the value “green” after the comprehension runs, being the last item iterated. To extract a specific item, it’s suggested to utilize a for loop with a break statement for clarity:
🌐
Python.org
discuss.python.org › ideas
A "for ... if" statement - Ideas - Discussions on Python.org
April 14, 2022 - What do people think about a simple (in theory?) addition to the for loop to make the following valid Python: for val in iterator if predicate(val): # do stuff with val This would be equivalent to for val in iterator: if predicate(val): # do stuff with val The closest you can get currently I think is for val in (val for val in iterator if predicate(val)): # do stuff with val or for val in filter(predicate, iterator): # do stuff with val The first form feels just a...
🌐
GoLinuxCloud
golinuxcloud.com › home › programming › python one line if else
How to use python if else in one line with examples
December 31, 2023 - If nesting deepens, switch to a ... standard if ladder. Inside comprehensions, the conditional-expression form filters or maps per element. That pairs naturally with loops written in one expression; see Python for loop in one line for the surrounding comprehension patterns. ... You should see ['odd', 'even', 'odd', 'even']. Use a conditional expression when you assign or return a single value from ...
🌐
Medium
medium.com › @chenyumei8866 › 20-extremely-useful-single-line-python-codes-bc553ea4832a
20 extremely useful single-line Python codes | by Python Data Development | Medium
January 8, 2023 - For loops are multi-line statements, but in Python, we can write for loops in one line using list comprehension methods. As an example, to filter out values less than 250, take a look at the following code example.
🌐
Built In
builtin.com › software-engineering-perspectives › can-you-put-a-for-loop-in-an-if-statement
Can You Put a For Loop in an If Statement? | Built In
For loops complete an iterative action for a defined number of elements, while if statements test a condition and then complete an action. Here’s how to combine them in Python.
🌐
Reddit
reddit.com › r/learnpython › if-else condition in one liner
r/learnpython on Reddit: If-else condition in one liner
August 21, 2023 -

There's this common syntax 'a' if condition else 'b' and I found it more readable and faster to write, but recently I ran into problem like this

# basically means if A exists, it covers the previous one, else prev becomes A. usually used within a loop.

lst = ['x', '', 'y']

prev = None
for x in lst:
    if x:
        prev = x
    else:
        x = prev

Somehow I cannot write this into prev = x if x else x = prev .

I kind of get it why this is an error but I just wonder if there's a better way to write this kind of code?

Top answer
1 of 5
3
for x in lst: _prev = x if x else prev What could why do you need x to be overwritten before it’s next loop…can now just use prev for the rest of the code block. x, _prev = (x,x) if x else (_prev, _prev) This should illuminate though why it’s seem pretty ridiculous to need. And give you a direct answer yes we can do this if we really wanted. But x won’t change the list, to do that we should….just make a new list. new_replace = [] _prev = None for x in my_list: _prev = x if x else _prev #do_something(_prev) new_replace.append(_prev) We can one line this…well two line technically, maybe if the first value is never empty we can omit, not sure. _prev = None _replace = [(_prev := x if x else _prev) for x in my_list] Pretty straightforward use of the walrus operation. (All we are doing is assigning and returning at the same time.) At this point you can just throw walrus into whatever function itself. And get right to it. And forget about it lists and stuff. _prev = None for x in my_list: no_empty_function(_prev := x if x else _prev) This is actually a fairly fast progression of a concept. And IMHO significantly “one lined”. (Though we can go further.) Or some enumerate() stuff but it honestly screams walrus function. I don’t need to make indexes and reference them, I already used the last value I just use it again. All that referencing get troublesome with huge datasets. Now my_list can be my_generator.
2 of 5
2
You can use or ( prev = x or prev ) or my personal favorite, a ternary operator: prev = x ? x : prev
🌐
Finxter
blog.finxter.com › home › learn python blog › python one line for loop [a simple tutorial]
Python One Line For Loop [A Simple Tutorial] - Be on the Right Side of Change
March 23, 2024 - Again, you can use list comprehension [i**2 for i in range(10) if i%2==0] with a restrictive if clause (in bold) in the context part to compress this in a single line of Python code.
🌐
Medium
medium.com › @andrewdass › python-how-to-make-and-use-single-line-for-loops-3dbadb2ab811
Python: How to Make and Use Single Line For Loops | by Andrew Dass | Medium
January 22, 2025 - In a one line for loop statement, the variable is written first and then the for loop statement. ''' Below shows the variable numbers_in_a_list is assigned to data that is casted within a list ''' numbers_in_a_list = [number for number in range(1, 10)] print(numbers_in_a_list) In Python, lambda functions are written in one line to first declare variables and then a statement that uses the declared variables to perform an operation. Single line for loops are often used with lambda functions...
🌐
sebhastian
sebhastian.com › python-one-line-for-loop
Python one line for loop tutorial | sebhastian
February 22, 2023 - List comprehension allows you to create a list and do operations on the list items in one line. You also don’t have to declare a list variable before running the list comprehension. Next, let’s see how to add an if statement in a list comprehension · If you want to create a list that fulfills a certain condition, you can add an if statement to the list comprehension. For example, say you want to create a list of even numbers from a range. This is how you do it with a regular for loop:
🌐
LearnPython.com
learnpython.com › blog › python-if-in-one-line
How to Write the Python if Statement in one Line | LearnPython.com
Here’s the basic structure: ... As you can see, not much has changed. We simply need to “pull” the indented line <perform_action> up to the right of the colon character (:). It’s that simple! Let’s check it with a real example.
🌐
Medium
medium.com › geekculture › 12-python-one-liners-that-you-must-know-c92165ce2558
12 Python One-Liners That You Must Know | by Haider Imtiaz | Geek Culture | Medium
August 18, 2021 - Do you know you can write the For loop in one line with its condition? #example codemylist = [4, 6, 8, 1, 3]for x in mylist: print(x)#Output # 4 # 6 # 8 # 1 # 3 · You can use simple if-else in one line.