[Tutor] Beginner's question: Looping through variable & list simultaneously

Mark Lawrence breamoreboy at yahoo.co.uk
Tue Dec 3 17:40:13 CET 2013


On 03/12/2013 16:15, Steven D'Aprano wrote:
> On Tue, Dec 03, 2013 at 04:04:33PM +0000, Mark Lawrence wrote:
>> On 03/12/2013 15:51, Steven D'Aprano wrote:
>>>
>>> Here's a modification to your earlier code using zip:
>>>
>>> PopularCountries = ["Brazil", "China", "France", "India", "Vietnam"]
>>> Backpackers = 1000000
>>> msg = "In %d there were %d backpackers worldwide and their most popular
>>> country was %s."
>>> for year, country in zip(range(2009, 2014), PopularCountries):
>>>      Backpackers = Backpackers*1.15
>>>      print(msg % (year, Backpackers, country))
>>>
>>
>> So much for "There should be one-- and preferably only one --obvious way
>> to do it." :)
>
>
> Huh? Using zip to iterate over multiple sequences in parallel *is* the
> obvious way to, um, iterate over multiple sequences in parallel.
>

Correct, except that there never was a requirement to iterate over 
multiple sequences in parallel.  The OP originally asked for "... how I 
can loop through a variable and a list at the same time."  I immediately 
thought enumerate, both yourself and Dave Angel thought zip.  We get the 
same output with different ways of doing it, hence my comment above.

-- 
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.

Mark Lawrence



More information about the Tutor mailing list