Conditions in List Comprehension in Python
If you need to set a condition in inclusion, it is written to the right of the iterated object (list, range of numbers):
list = [expression for element in iter if condition]
When generating a list, you can specify 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]
Use include to make a list with only odd elements:
[1, 3, 5, 7, 9]
Given a list:
lst = [-6, -3, -1, 0, 2, 4]
Use inclusion to make a new list out of it that contains only positive numbers, including zero.