Question:
Create a list of even numbers between 0 and 10 using list comprehension.
Program:
1 2 |
listl=[i for i in range (10) if(i%2==0)] print listl |
Explanation:
List comprehensions provide a concise way to create lists.
It consists of brackets containing an expression followed by a for clause, then
zero or more for or if clauses. The expressions can be anything, meaning you can
put in all kinds of objects in lists.
List comprehensions provide a concise way to create new list of elements that satisfy a given condition from an iterable. Here the iterable prints out even numbers.
Output:
1 |
[0, 2, 4, 6, 8] |
Leave a Reply