List comprehension allows creating a new list from another sequence or iterable.
List comprehensions in Python are constructed as follows:
list_variable = [x for x in iterable one_or_more_condition]
A list comprehension consists of the following parts:
Suppose, we need to find the squares of all the even
integers of a given list.
a_list = [1, 4, 6, 5]
squared_list = [ i**2 for i in a_list if i%2 == 0 ]
print(squared_list)
output: [16, 36]
Here, square brackets indicate that the output is a list.
even
number.even
number then it is passed to the output expression, squared, to become a member of the output list.The same result can be achieved using for
loop
a_list = [1,4,6,5]
output_list = []
for i in a_list:
if i%2 ==0:
output_list.append(i**2)
print("Output List using for loop:", output_list)
output: [16, 36]
#programming #python3 #list-comprehension #python27