0

I am new in python and I was wondering the following. I have two matrices g1 and g2 and I would like to run a for loop for all the values of g1 and then g2.

I initially thought I could do:

for A in g1:
   .....

for A in g2:
   .....

But I was wondering if there is a way to run both at the same for loop. Eg. I tried this but it didn't work

for A in g1,g2:
KonK3
  • 81
  • 1
  • 7

3 Answers3

1

You can use zip to iterate both iterables at the same time:

l = [1, 2, 3]
l2 = [4, 5, 6]
for x, y in zip(l, l2):
    print x, y

1 4
2 5
3 6

zip() function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The returned list is truncated in length to the length of the shortest argument sequence.

Chen A.
  • 10,140
  • 3
  • 42
  • 61
1

You can use zip() to iterate on two lists at once.

one = [1,2,3,4]
two = [5,6,7,8]
for elem1, elem2 in zip(one, two):
    print(elem1, elem2)

Prints out this:

(1, 5)
(2, 6)
(3, 7)
(4, 8)
ProfOak
  • 541
  • 4
  • 10
0

First, you should check the two data in the two loop is independent. Then you could merge the two loop in one.

Charles Cao
  • 116
  • 4