In this blog, we will create a list of 3 elements then use while loop to append new elements in a list. If user input ‘q’ then the while will be terminated and at the last display elements in the list
Create a list with three values. In below statement, we have created city list with 3 elements inside it
city = ['Paris','London','Mumbai']
Now use while loop to append or add new elements at the end. We will ask user to input city name and append that city in to the list. When user presses ‘q’ key, while loop will terminate
while city: new_city = input('Enter a city name: ') if new_city == 'q': break city.append(new_city)
Output
Enter a city name: Tokyo Enter a city name: Beijin Enter a city name: q ['Paris', 'London', 'Mumbai', 'Tokyo', 'Beijin']
Complete Code
city = ['Paris','London','Mumbai'] while city: new_city = input('Enter a city name: ') if new_city == 'q': break city.append(new_city) print(city)