List Comprehension

Beginning Python Programming

Makzan, 2020 April.

List Comprehension

  • From for-loop to list comprehension
  • List comprehension with if condition

Example: for-loop approach

L = range(1,10)
for x in L:
  print(x*x)

Example: for-loop approach

L = range(1,10)
L2 = []
for x in L:
  L2.append( x*x )
print(L2)

Example: list comprehension

L2 = [x*x for x in range(1,10)]
print(L2)

Example: list comprehension

L2 = [x*x for x in range(1,10)]
L2 = []
for x in range(1,10):
  L2.append( x*x )
print(L2)

1. Construct a new list

2. The list source is an iteration

3. Each new element is calculated from the source element.

4. Result list

List comprehension with if

scores = [34, 65, 45, 67, 78, 56, 80]
passed_scores = [x for x in scores if x >= 60]
print(passed_scores)

# Result:
# [65, 67, 78, 80]

List comprehension with if

scores = [34, 65, 45, 67, 78, 56, 80]
L = [x for x in scores if x >= 60]
L = []
for x in scores:
  if x >= 60:
    L.append(x)

1. Construct a new list

2. The list source is an iteration

4. Each new element is calculated from the source element.

5. Result list

3. Add to the list according to condition

Conclusion


scores = [34, 65, 45, 67, 78, 56, 80]
L = [x for x in scores if x >= 60]