OKPEDIA PYTHON LISTA EN

What is the list comprehension in Python

List comprehension is a construct used in Python to create a list from a generating expression.

list = [expression]

The generating expression is placed in square brackets.

List comprehension allows you to automatically create a multi-element list without using loops and iterations.

Examples

Example 1

Create a list with powers of numbers from 1 to 10.

>>> lista = [x**2 for x in range(1,11)]

List comprehension creates a list with numbers from 1 to 10 to the power of 2.

>>> lista
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Example 2 ( list comprehension with IF )

Create a list with squares of even numbers.

Just add an if to the previous example

>>> lista = [x**2 for x in range(1,11) if x%2==0]

The condition if x%2==0 selects numbers divisible by two with remainder equal to zero, i.e. even numbers.

The contents of the list is

>>> lista
[4, 16, 36, 64, 100]

List comprehension selects and raises to the power of two only the even numbers between 1 and 10.

https://how.okpedia.org/en/python/what-is-the-list-comprehension-in-python


Report an error or share a suggestion to enhance this page


Python List


FacebookTwitterLinkedinLinkedin