Is it possible that with the use of list comprehension to iterate through two variables at the same time increasing the loop position in both at the same time. See example below:
a = [1,2,3,4,5]
b = [6,7,8,9,10]
c = [i+j for i in a for j in b] # This works but the output is not what it would be expected.
expected output is c = [7, 9, 11, 13, 15]
(n'th element from a + n'th element from b)
Thank you.
No, you cannot use while in a list comprehension.
As we can see, the for loop is slower than the list comprehension (9.9 seconds vs. 8.2 seconds). List comprehensions are faster than for loops to create lists. But, this is because we are creating a list by appending new elements to it at each iteration.
The list comprehension is 50% faster.
a = [1,2,3,4,5]
b = [6,7,8,9,10]
c = map(sum, zip(a, b))
print c
#Output
[7, 9, 11, 13, 15]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With