Anonymous
Anonymous

Reputation: 355

How to iterate over two lists without using nested for loops?

If a and b are two lists then how can we get c without using nested for loops in python?

a=[1,2,3] 
b=[4,5,6] 
c=[(1,4),(1,5),(1,6),(2,4),(2,5),(2,6),(3,4),(3,5),(3,6)] 

Let's assume I have to find the sum of all nth term of fibonacci sequence formed by these pairs as the first two numbers, where n is any positive number. In this case for n=3 answer in 63.

>     1 4 5 nth term in 5  1 5 6 nth term in 6  . . . 3 6 9 nth term in 9 
>            > Sum of all nth term in 63.

Upvotes: 2

Views: 1571

Answers (2)

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48357

Just use product method from itertools package.

a=[1,2,3] 
b=[4,5,6]
c = list(itertools.product(a,b))
print(c)

Output

[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]

Upvotes: 4

cmaher
cmaher

Reputation: 5215

Here's an alternative approach with numpy:

import numpy as np

zip(np.repeat(a, 3), np.tile(b, 3))

# [(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]

Upvotes: 1

Related Questions