How do I have a user input a list?

Viewed 52

I need to have users input a list for my program in order for it to work properly, and the list needs to be formatted like [1,1,2]. This is the code gathering the list input:

entry = list(input(": "))

I was having some problems and put it through a debugger and saw that the list was showing up as this: enter image description here

How can I make it work correctly?

1 Answers

While its possible to evaluate a list like that, it's not good practice as evaluating anything can introduce many edge cases.

A better solution would be to have the user input the values of the list either all at once:

entry = list(input("Enter the values: ").split(","))
# User enters: 1,2,3,4,5
# List ends up as: [1, 2, 3, 4, 5]

or one at a time

endChar = '$' # Setting end character
in = '' # Clearing user input variable
chars = [] # List of values
print("Enter your values, use '$' to finish.") # User prompt
while in != endChar: # Continue until $ is entered
    in = input("Value: ") # Get value
    chars.append(in) # Add element to list
print(chars) # Finished list
Related