Member-only story
4 Ways To Write One-Liner For Loops in Python
Loop through lists, dictionaries, sets, and generators with a neat shorthand without sacrificing readability

In Python, you can turn your for
loops into one-liners by using comprehensions.
Python supports four different types of comprehensions for the main sequence types:
- List comprehensions
- Dictionary comprehensions
- Set comprehensions
- Generator comprehensions
All the comprehensions look pretty similar to one another, and they are simple and beginner-friendly. Without further ado, let’s take a look at some examples of how to work with comprehensions in Python.
List Comprehensions
Let’s start by creating a new list of numbers based on an existing list by leaving all the negative numbers out. You can use a for
loop to solve this task:
Output:
[4, 7, 19]
But you can also make this whole for
loop shorter, more readable, and professional by using a list comprehension:
new_nums = [num for num in numbers if num > 0]print(new_nums)
Output:
[4, 7, 19]
Congrats! You just saved four lines of code without sacrificing readability.
To wrap it up, here is the general structure of the list comprehension:
output_list = [expression for var in input_list if condition]
For the sake of clarity, the if condition
is optional. For example, consider squaring the numbers
list using list…