Last modified: Jul 03, 2023 By Alexander Williams
Using While Loop to Append to List in Python
To append items to a list using a while
loop, follow these steps:
- Initialize an empty list.
- Define the condition that determines when the loop should exit.
- Prompt the user for input or generate the items programmatically.
- Use the
append()
method to add each item to the list. - Update the condition or exit the loop when the desired criteria are met.
Let's see an example:
names = [] # Initialize an empty list
while True: # Set the condition to always be True
name = input("Enter a name (enter 'quit' to exit): ")
if name.lower() == "quit":
break # Exit the loop if the user enters "quit"
names.append(name) # Append the name to the list
print(names) # Print the final list of names
In this example, the loop will continue until the user enters "quit".