Better Programming

Advice for programmers.

Follow publication

Member-only story

4 Ways To Write One-Liner For Loops in Python

Artturi Jalli
Better Programming
Published in
4 min readApr 22, 2021

--

Drawing of code on monitor
Photo by the author.

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…

--

--

Responses (1)

Write a response