List Comprehension
List comprehension allows us to easily fill out contents of a list in a single line of code.
For example, if we wanted to fill a list with the first 5 even numbers, we would write something like this:
l = []
for i in range(5):
l.append(2 * i)
print(l) # Prints [0,2,4,6,8]
While not a terribly hard task to do, it takes 4 lines of code to do so. We can shorten it by using list comprehension.
Syntax
List comprehension follows the following syntax:
lst = [expression for thing in iterable]
Here, expression
is the value that is going to be applied into the list. This can be the form of any valid Python code, so functions, addition, multiplication, etc.
thing
stands for any variable that can be returned by iterable.
Using list comprehension, we can simplify the first example to the following:
l = [2 * i for i in range(5)]
print(l) # Prints [0,2,4,6,8]
Conditional Clause
Python’s list comprehension also allows us to filter out results based on a conditional statement. The syntax is as follows:
lst = [expression for thing in iterable if condition]
Condition
being and valid conditional statement. For Example:
odd_nums = [i for i in range (10) if i % 2 == 1]
print(odd_nums) # Prints [1, 3, 5, 7, 9]