⊗pyPmCoLi 25 of 128 menu

List Comprehensions in Python

List comprehensions allow you to generate lists by applying a given expression to each element of the future list. You can also use comprehensions to filter elements according to given conditions.

The inclusion specifies an expression that will be applied to the elements of the original list. The for...in construct specifies the name of the element and the original list (iterable object) from which the new one will be created:

list = [expression for element in iter]

Let's declare a variable lst. We'll write for it that the list element i should be generated in the range 1 to 10. Then we'll output the resulting list to the console:

lst = [i for i in range(1, 10)] print(lst)

After executing the code, a new list will be returned:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

Using the inclusion, make the following list:

[1, 2, 3, 4, 5]

Using the inclusion, make the following list:

[5, 4, 3, 2, 1]
enru