How to Create a List from User Input in Python?

Estimated read time 1 min read

You can create a list from user input in Python using the input() function and a loop. Here’s an example:

my_list = []

n = int(input("Enter the number of elements: "))

for i in range(n):
    element = input("Enter an element: ")
    my_list.append(element)

print("The list is:", my_list)

In this example, we first create an empty list my_list. We then use the input() function to get the number of elements from the user, which we convert to an integer using the int() function.

We use a for loop to iterate n times, asking the user to input an element each time using the input() function. We append each element to the my_list using the append() method.

Finally, we print the contents of the list using the print() function.

Note that the input values will be treated as strings, so you may need to convert them to the appropriate data type (e.g., int, float) depending on your use case.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply