1
486views
What is list comprehension? explain with example.
1 Answer
written 2.6 years ago by |
Solution
List Comprehension
ex: (using for loop)
input :
mystr = 'ques'
mylist = [ ]
for c in my str:
mylist.append(c)
print(mylist)
output : ['q', 'u', 'e', 's']
Syntax :
[ expression for item in iterable ]
OR
[ expression for item in iterable if condition ]
Example (using List Comprehension):
mylist = [c for c in 'ques']
print(mylist)
output : ['q', 'u', 'e', 's']
Example (Using for loop):
mylist = [ ]
for i in range(1,6):
mylist.append(i**2)
print(mylist)
output : [1, 4, 9, 25]
Example (using List Comprehension):
mylist = [i**2 for i in rang(1,6) ]
print(mylist)
output : [1, 4, 9, 25]