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:

  1. Initialize an empty list.
  2. Define the condition that determines when the loop should exit.
  3. Prompt the user for input or generate the items programmatically.
  4. Use the append() method to add each item to the list.
  5. 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".