⊗pyPmCoLC 28 of 128 menu

Conditions in List Comprehensions in Python

If you need to set a condition in a comprehension, it is written to the right of the iterable object (list, range of numbers):

list = [expression for element in iter if condition]

When generating a list, you can set additional conditions for its elements. Let's write a condition according to which only even elements from the range from 1 to 10 will be included in the list:

lst = [i for i in range(1, 10) if i % 2 == 0] print(lst)

After executing the code, a new list with even elements will be output:

[2, 4, 6, 8]

Using a comprehension, create a list containing only the odd elements:

[1, 3, 5, 7, 9]

Given the list:

lst = [-6, -3, -1, 0, 2, 4]

Using a comprehension, create a new list from it that contains only the positive numbers, including zero.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline