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:

  • An Input Sequence.
  • A Variable representing members of the input sequence.
  • An Optional Predicate expression.
  • An Output Expression producing elements of the output list from members of the Input Sequence that satisfy the predicate.

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.

  • The iterator part iterates through each member i of the input sequence a_list.
  • The predicate checks if the member is an even number.
  • If the member is an 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

A Walk Through Python List Comprehension
1.45 GEEK