Python - Iteration and Optimization

Introduction

The following list comprehension expression computes the squares of a list of numbers:

Demo

squares = [x ** 2 for x in [1, 2, 3, 4, 5]] 
print( squares )

Result

can always be coded as an equivalent for loop that builds the result list manually by appending as it goes:

Demo

squares = [] 
for x in [1, 2, 3, 4, 5]:          # This is what a list comprehension does 
    squares.append(x ** 2)         # Both run the iteration protocol internally 
# ww  w .  j  a v  a 2s .  c  om
print( squares )

Result

Both tools use the iteration protocol internally and produce the same result.

Related Example