+ 9
Can anyone explain me what is list comprehension in python with easy example?
2 Answers
+ 6
its making a list (or other containers) without several lines of code.
nums = [1,2,3,4,5]
# ====== getting squared values =====
# regular syntax
squ = []
for n in nums:
squ.append(n*n)
OR
# list comp
squ1 = [n*n for n in nums]
BOTH squ and squ1 will contain the squared values of 1-5: [1,4,9,16,25]
+ 10
#It's Tony Stark , a while ago, i did a small tutorial how to turn a regular for loop to a comprehension:
https://code.sololearn.com/cqnGujvL7CXe/?ref=app