[Tutor] Beginner's question: Looping through variable & list simultaneously
Alan Gauld
alan.gauld at btinternet.com
Tue Dec 3 19:55:21 CET 2013
On 03/12/13 12:55, Rafael Knuth wrote:
> Now I want to enhance that program a bit by adding the most popular
> country in each year. Here's what I want to get as the output:
>
>>>>
> In 2009 there were 1150000 backpackers worldwide and their most
> popular country was Brazil.
...
> From all my iterations there's only one that came at least halfway
> close to my desired result:
>
> PopularCountries = ["Brazil", "China", "France", "India", "Vietnam"]
> Backpackers = 1000000
> for x in range(2009, 2014):
> Backpackers = Backpackers*1.15
> PopularCountries = PopularCountries.pop()
> print("In %d there were %d backpackers worldwide and their most
> popular country was %s." % (x, Backpackers, PopularCountries))
>
> It loops only once through "Backpackers" and "PopularCountries"
> (starting with the last item on the list though) and then it breaks:
Others have pointed to better solutions. However, the reason this one
breaks is that you are using the same variable name for your country
inside the loop as for the collection.
PopularCountries = PopularCountries.pop()
This replaces the collection with the last country; a string.
That's why you get the error. Now, if you use a different name
like:
PopularCountry = PopularCountries.pop()
And print the new name the problem should go away.
> Is there a way to use pop() to iterate through the list in a correct
> order (starting on the left side instead on the right)?
Yes, just provide an index of zero:
PopularCountry = PopularCountries.pop(0)
> If not: What alternative would you suggest?
See the other answers. zip is probably better.
HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list