Python List Comprehension: One-Liner For Loops
Comprehensions offer a smooth approach for creating new sequences in a concise and readable way.
Python List Comprehension makes it possible to write concise one-liners for loops.
For instance, you can use a comprehension to replace 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]
if condition part is optional
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:
[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: