+ 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 ?
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)
+ 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
+ 1
Thanks š