0

I would like to loop as something like:

for j in range(1,4) and for k in ['one', 'two', 'three']:
               print(str(j) + ' is written ' + k)

I tried with and but it didn't work. How does someone get this effect?

And what would happen in the case that the two lists have different lengths? How could I still iterate through both of them?

3 Answers 3

7

You can use zip

for j, k in zip(range(1,4), ['one', 'two', 'three']):
    print('{} is written {}'.format(j, k))    

1 is written one
2 is written two
3 is written three

If one is longer than the other, you could consider using itertools.zip_longest

Sign up to request clarification or add additional context in comments.

Comments

7

Check this out:

for j,k in enumerate(['one', 'two', 'three'], 1):
    print("{} is written {}".format(j, k))

Comments

4

You should zip 'em all!

for j, k in zip(range(1,4), ("one", "two", "three")):
    # use j and k

3 Comments

I choose you zipachu!
Why two downvotes?? You don't like Pokémon? Or the zip function?
Not the downvoter, but I think there might be debate between which answer might be better between zip and enumerate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.