CODEX

Python List Comprehension: One-Liner For Loops

Comprehensions offer a smooth approach for creating new sequences in a concise and readable way.

Artturi Jalli
CodeX
Published in
3 min readFeb 11, 2021
Photo by Sebastian Willius on Unsplash

Python List Comprehension makes it possible to write concise one-liners for loops.

For instance, you can use a comprehension to replace this:

With this:

There are actually 4 different comprehensions in Python for the main collection types:

  • List Comprehensions
  • Dictionary Comprehensions
  • Set Comprehensions
  • Generator Comprehensions

Python List Comprehension

Here is the general structure for list comprehension for your convenience:

[expression for var in input_list if condition]

Where the if condition part is optional

Example

Say you have a list of numbers and you want to exclude all the negatives. Using a for loop to iterate over the list of numbers is nothing new:

Output:

[1, 3, 5]

However, if you want to bring it to the next level, you can make this whole for loop shorter by using list comprehension:

--

--

Artturi Jalli
CodeX
Writer for

Youtube: @jalliartturi—learn blogging without SEO