Question

I have an issue with printing out an item from a list.

Here's the relevant code:

countryList = []

cityList = []

def startFunction():
     while True:
        print("\nWhen you have typed in country and city, press 3 in the menu to see the weather forecast for your choice.\n")
        menu = input("\nPress 1 for country\nPress 2 for city\nPress 3 to see forecast\nPress 4 to exit\n")
        if menu == "1":
            countryFunction()
        elif menu == "2":
            cityFunction()
        elif menu == "3":
            forecastFunction()
        else: 
            print ("\nGoodbye")
            break

I first have an empty list for country and city and then a startfunction with a loop which will call the different functions.

Here's in how the function for choosing the country looks like:

def countryFunction():
    countryc = input("Enter which country your city is in(in english): ")
    countryList.append(countryc)

And then the print function looks like this:

def forecastFunction():
    r = requests.get("http://api.wunderground.com/api/0def10027afaebb7/forecast/q/" + countryList[0] + "/" + cityList[0] + ".json")
    data = r.json()
    #Above is the problem, countryList[0] and cityList[0]  

As you can see at the moment I've just put countryList[0] but that will only print out the first item of the list. And because of the loop I'm using, the user is able to choose country and city over and over again, which will append to the list everytime. My question is: How do I print out the last list-item(the last item appended to the list) in the code
r = requests.get("http://api.wunderground.com/api/0def10027afaebb7/forecast/q/" + countryList[0] + "/" + cityList[0] + ".json"

Was it helpful?

Solution

Use -1 as the index to the list, i.e. countryList[-1] will give you the last item in the list.

Although the tutorial shows an example as indexing of strings, it works the same for lists: http://docs.python.org/2/tutorial/introduction.html#strings

OTHER TIPS

Too long for a comment:

As the other answer points out, you just need to use the -1 index feature, as in countryList[-1].

However, it also seems like you'd like to use an ordered set-like data structure, to avoid storing repeated entries from users. In that case, using OrderedDict might be better for you.

Or perhaps have a look at the OrderedSet recipe.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top