Write a python program to add elements to an existing list from user input

1. Introduction

In this blog post, we will create a Python program that adds elements to an existing list based on user input. This task is a common operation in Python and is a great way to understand how lists work and how to interact with user input.

2. Program Steps

1. Start with an existing list.

2. Prompt the user to enter an element to add to the list.

3. Add the user's input to the list.

4. Repeat steps 2 and 3 a certain number of times or until a specific condition is met.

5. Display the updated list.

3. Code Program


def add_elements_to_list(existing_list):
    # Number of elements to add
    num_elements = int(input("How many elements would you like to add? "))

    # Step 2 and 3: Adding elements to the list
    for i in range(num_elements):
        new_element = input(f"Enter element {i+1}: ")
        existing_list.append(new_element)

    # Step 5: Display the updated list
    print("Updated List:", existing_list)

# Step 1: Start with an existing list
initial_list = [1, 2, 3]
add_elements_to_list(initial_list)

Output:

The output will display the updated list after adding the user-input elements. For example, if the user chooses to add 2 elements, 'Python' and '4', the output will be:
Updated List: [1, 2, 3, 'Python', '4']

Explanation:

1. The function add_elements_to_list starts with an existing_list.

2. It prompts the user to specify how many elements they want to add using input() and converts this number to an integer.

3. A for loop is then used to iterate the specified number of times. Each iteration prompts the user to input a new element.

4. The user-input element is added to existing_list using the append() method.

5. After all elements are added, the updated list is printed.

This program demonstrates how to interact with the user and modify lists in Python, showcasing basic list manipulation and user input handling.


Comments