List Comprehension in Python
list can be created in this was-
list_variable= [ x for x in iterable]
v=(1,4,9,16,25,36)
now list comprehension can be use as-
v=[x**2 for x in range(7)]
Using for loop for getting even numbers in 10 natural numbers-
numbers= range(10)
newlist=[]
for i in numbers:
if i%2 == 0:
newlist= new_list.append(i)
print(newlist)
Using list comprehension to do the same:
newlist= [x for x in numbers if x%2 == 0]
print(newlist)
output in both the case-
[0,2,4,6,8]
list_variable= [ x for x in iterable]
v=(1,4,9,16,25,36)
now list comprehension can be use as-
v=[x**2 for x in range(7)]
Using for loop for getting even numbers in 10 natural numbers-
numbers= range(10)
newlist=[]
for i in numbers:
if i%2 == 0:
newlist= new_list.append(i)
print(newlist)
Using list comprehension to do the same:
newlist= [x for x in numbers if x%2 == 0]
print(newlist)
output in both the case-
[0,2,4,6,8]
Comments
Post a Comment