+ 2

python

What is the output of this code ? l = [x for x in range(1,5)] f = [2 if x % 2 else 1 for x in l] n= [x*s for x,s in zip(l,f)] print(sum(n)) Output: 14 why 14 ?

4th Dec 2022, 2:38 PM
Game0ver
Game0ver - avatar
3 Answers
+ 3
print each list l = [x for x in range(1,5)] print(l) f = [2 if x % 2 else 1 for x in l] print(f) n= [x*s for x,s in zip(l,f)] print(n) print(sum(n)) l is list of numbers from 1, 2, 3, 4. f is 2, 1, 2, 1 because in the list comprehension, it will append 2 if the number is odd and 1 if even for x in l. (odd, x%2==1 is True, so 2 is appended, else 1) n is just the product of the items of list l and f with the same index. (zip function)
4th Dec 2022, 2:50 PM
Bob_Li
Bob_Li - avatar
+ 2
l = [ 1,2,3,4 ] #range(1, 5) f = [ 2,1,2,1 ] # odd 2, even 1 n = [ 1*2 , 2*1, 3*2, 4*1 ] = [ 2, 2, 6, 4 ] #zip(l, f) sum(n) => 2+2+6+4= 14
4th Dec 2022, 2:48 PM
Jayakrishna 🇮🇳
Jayakrishna 🇮🇳 - avatar
+ 1
Thanks 🙏
4th Dec 2022, 2:57 PM
Game0ver
Game0ver - avatar