Site icon Meccanismo Complesso

Python Lessons – 5.6 List Comprehension

Python Lessons - 5.6 List comprehension m
Python Lessons - 5.6 List comprehension

List Comprehension

List comprehension is an excellent technique for creating lists whose content obeys simple rules (do you remember numerical sequences 😉 ).

For example if you want a list with the first five numbers squared.

lista = [i**2 for i in range(5)]
print(lista)

if you run it, you get

>>>
[0, 1, 4, 9, 16] 

In addition there are also list comprehensions with a more complex construct that in addition to the for loop also has an if clause. For example if we wanted only the even values of the previous list.

lista = [i**2 for i in range(5) if i**2 % 2 == 0]
print(lista)

if you run it, you get

>>>
[0, 4, 16]

⇐ Go to Python Lesson 5.5 – Slicing lists 

Go to Python Lesson 5.7 – String formatting ⇒

Exit mobile version