Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehension iterate two variables at the same time [duplicate]

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.

like image 481
Ignasi Avatar asked Jul 08 '16 14:07

Ignasi


People also ask

Can we use while loop in list comprehension?

No, you cannot use while in a list comprehension.

Is list comprehension more efficient than for loop?

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.

Is list comprehension faster than appending?

The list comprehension is 50% faster.


1 Answers

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]
like image 191
Jeremy Avatar answered Oct 07 '22 17:10

Jeremy