Skip to content

Python one line if-else for a loop | Example code

  • by

Simple Python one line if-else for a loop example code.

>>> [(i) for i in my_list if i=="two"]
['two']

For loop and if-else condition in one line python

If and else inside a one-line python loop. Counting how many numbers in the list is above the 20.

list1 = [10, 25, 36, 24]
count = 0
for i in list1: count = count + 1 if i > 20 else count

print(count)

Output:

Python one line if-else for a loop

One-line list comprehension: if-else variants

A list comprehension that produces a list of odd numbers of a given range.

oddnum = [x for x in range(1, 10) if x % 2]

print(oddnum)

Output: [1, 3, 5, 7, 9]

Do comment if you have any doubts and suggestions on this Python Loop topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading