Search code examples
listwhile-looppython-3.7

Python 3.7 : Why is only the last item in a list printing?


I am self-studying "Python Crash Course" 2nd edition and I have come upon a problem that I am unable to solve. I have reread previous areas of the book, searched the internet and search other SO answers.

The official book answer uses a dictionary but I am trying to use a list.

The program should ask for input, add the input to a list and continue to repeat until told to stop. When told to stop, the entire list should be printed.

The problem that I am running into is that only the last item in the list in printing.

Instead of giving the answer, please just give me a hint so that I can truly learn.

Thanks,

chadrick

active = True
while active == True:
    places = []
    place = input("\nIf you could visit one place in the world, where would you go? ")
    places.append(place)
    repeat = input("Would you like to let another person respond? (yes/no) ")
    if repeat == 'no':
        print(places)
        active = False

Solution

  • The reason is because you're resetting the list back to empty for every iteration.

    try the following:

    active = True
    places = []
    while active == True:
        place = input("\nIf you could visit one place in the world, where would you go? ")
        places.append(place)
        repeat = input("Would you like to let another person respond? (yes/no) ")
        if repeat == 'no':
            print(places)
            active = False
    

    Also, since active is a boolean, you just need to do while active:

    So:

    active = True
    places = []
    while active:
        place = input("\nIf you could visit one place in the world, where would you go? ")
        places.append(place)
        repeat = input("Would you like to let another person respond? (yes/no) ")
        if repeat == 'no':
            print(places)
            active = False