Reputation: 3561
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?
Upvotes: 0
Views: 71
Reputation: 113905
Check this out:
for j,k in enumerate(['one', 'two', 'three'], 1):
print("{} is written {}".format(j, k))
Upvotes: 7
Reputation: 44828
You should zip
'em all!
for j, k in zip(range(1,4), ("one", "two", "three")):
# use j and k
Upvotes: 4
Reputation: 117856
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
Upvotes: 7