Instead of using the same old way of iterating through lists, we can make our code simpler by using list comprehensions, which allow us to make a 1 line for loop in Python.
Basic syntax of a 1 line for loop
To use a one line for loop to replace a regular for loop, we can make:
[statement for i in list]
Which is the same as doing:
for i in list:
expression
If we want some conditional to apply the expression, we have:
[statement for i in list if condition ]
Which translates to:
for i in list:
if condition:
statement
Example 1: calculating the cube of a number
Regular way
numbers = [10, 20, 30, 40, 50]
new_list = []
for n in numbers:
new_list.append(n**3)
print(new_list)
[1000, 8000, 27000, 64000, 125000]
Using 1 line for loop
numbers = [10, 20, 30, 40, 50]
new_list = []
new_list = [n**3 for n in numbers]
print(new_list)
[1000, 8000, 27000, 64000, 125000]
Example 2: calculating the cube of a number only if it is greater than 30
Using the conditional, we can filter only the values we want the expression to be applied to.
Regular way
numbers = [10, 20, 30, 40, 50]
new_list = []
for n in numbers:
if(n > 30):
new_list.append(n**3)
print(new_list)
[64000, 125000]
Using 1 line for loop
numbers = [10, 20, 30, 40, 50]
new_list = []
new_list = [n**3 for n in numbers if n > 30]
print(new_list)
[64000, 125000]
Example 3: calling functions with a 1 line for loop
We can also call functions using the list comprehension syntax:
numbers = [10, 20, 30, 40, 50]
new_list = []
def cube(number):
return number**3
new_list = [cube(n) for n in numbers if n > 30]
print(new_list)
[64000, 125000]
To know more about loops, check these posts on for Loops in Python and While Loops in Python.