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

Rafael Knuth rafael.knuth at gmail.com
Tue Dec 3 16:03:55 CET 2013


Hej there,

> That's very poor coding, if you're given a function that does exactly what
> you want, why rewrite it and worse still, get it wrong?

I don't quite understand. I took that advice, tried it - it worked,
and then I figured out there's also another way to get there.
The output from the "for Country in range(len(PopularCountries))" is
exactly the same as with "enumerate", or am I missing something here?

>> PopularCountries = ["Brazil", "China", "France", "India", "Vietnam"]
>> Year = 2009
>> Backpackers = 1000000
>> for Country in range(len(PopularCountries)):
>>      Year += 1
>>      Backpackers = Backpackers*1.15
>>      print("In %d there were %d backpackers worldwide and their most
>> popular country was %s." % (Year, Backpackers,
>> PopularCountries[Country]))
>>
>>>>>
>> In 2010 there were 1150000 backpackers worldwide and their most
>> popular country was Brazil.
>
>
> Whoops, what happened to 2009?

Typo ;-)

>> In 2011 there were 1322500 backpackers worldwide and their most
>> popular country was China.
>> In 2012 there were 1520874 backpackers worldwide and their most
>> popular country was France.
>> In 2013 there were 1749006 backpackers worldwide and their most
>> popular country was India.
>> In 2014 there were 2011357 backpackers worldwide and their most
>> popular country was Vietnam.
>>
>> I will now try to further enhance my program by adding a second list
>> to the loop.
>
>
> What do you mean by "enhance", get the output correct or make it even worse?
> :)

Very funny. Couldn't stop laughing ;-)

> So here's the code with enumerate.
>
>
> PopularCountries = ["Brazil", "China", "France", "India", "Vietnam"]
> Backpackers = 1000000
> for x, PopularCountry in enumerate(PopularCountries, start=2009):
>     Backpackers = Backpackers*1.15
>     print("In %d there were %d backpackers worldwide and their most popular
> country was %s." % (x, Backpackers, PopularCountry))
>
> In 2009 there were 1150000 backpackers worldwide and their most popular
> country was Brazil.
> In 2010 there were 1322500 backpackers worldwide and their most popular
> country was China.
> In 2011 there were 1520874 backpackers worldwide and their most popular
> country was France.
> In 2012 there were 1749006 backpackers worldwide and their most popular
> country was India.
> In 2013 there were 2011357 backpackers worldwide and their most popular
> country was Vietnam.

Thanks. Just one last question: Is there a way to loop through an
arbitrary number of lists at the same time?
Say, if I wanted to loop through the most popular travel guides in
each year in addition to most popular country? I couldn't figure that
out by myself.
Would that be doable with "enumerate" as well?

All the best,

Raf


More information about the Tutor mailing list