user12351304
user12351304

Reputation:

Python "for loop" with 2 lists/variables

I have the following code:

def odraw(oposlist, osizelist):
    for opos in oposlist and osize in osizelist:
        pygame.draw.rect(screen, black, (opos[0], opos[1], osize[0], osize[1]))

How to rephrase the second line? How it is written right now obviously does not match the Python syntax.

Upvotes: 1

Views: 77

Answers (2)

user2390182
user2390182

Reputation: 73460

If you are looking for pairwise iteration, use zip:

for opos, osize in zip(oposlist, osizelist):

If, however, you want the cartesian product (pair every element in oposlist with every element in osizelist), use itertools.product ...

from itertools import product
# ...
for opos, osize in product(oposlist, osizelist):

... or simply nest loops:

for opos in oposlist:
    for osize in oposlist:
        # do stuff

Upvotes: 3

R4444
R4444

Reputation: 2114

You can do:

for i in range(len(oposlist)):
    # Refer oposlist and osizelist like
    oposlist[i]
    osizelist[i]

Tbh, other answer is better :-)

Upvotes: 2

Related Questions