In this tutorial, we will learn how to add names to a list in Python. We will create a simple program that takes user input for names and append them into a Python list. Additionally, we will discuss various methods to manipulate lists.
Step 1: Create an empty list
First, we need to create an empty list to store the names. In Python, lists can be created using square brackets. An empty list is represented by empty square brackets.
1 |
names_list = [] |
Step 2: Take user input for names
We can use the input() function to take user input in Python. It returns a string, which we can directly append to our list.
1 |
name = input('Enter a name: ') |
Step 3: Add names to the list
To add a name to the list, we can use the append() function of the list. This function takes an element as an argument and adds it to the end of the list.
1 |
names_list.append(name) |
Step 4: Loop to add multiple names
We can use a loop to continuously take input from the user and append the names to the list. In this example, we will use a for loop.
1 2 3 4 5 |
number_of_names = int(input('How many names do you want to add? ')) for i in range(number_of_names): name = input('Enter a name: ') names_list.append(name) |
Step 5: Print the names list
Finally, we can print the list of names to ensure they have been successfully added.
1 |
print(names_list) |
Complete Code:
1 2 3 4 5 6 7 8 9 |
names_list = [] number_of_names = int(input('How many names do you want to add? ')) for i in range(number_of_names): name = input('Enter a name: ') names_list.append(name) print(names_list) |
Output:
How many names do you want to add? 3 Enter a name: Alice Enter a name: Bob Enter a name: Carol ['Alice', 'Bob', 'Carol']
Conclusion
You have now learned how to add names to a list in Python. This tutorial covered the basics of creating an empty list, taking user input, appending elements to a list, and using a loop to add multiple names. You can further enhance this program by adding more functionalities such as sorting or filtering the list as per your needs. Don’t forget to keep practicing and exploring different ways of working with lists in Python.