I want to know how to take an input from the user as a list. For instance, there will be a message wanting input from the user and the user will input [1,2,3]. Then, the program will create a new variable with a type list and assign the input to that variable. (I've tried to use the enter code function but I couldn't figure it out since It's my first time asking a question so, that's why I explained my code instead of writing it)
Asked
Active
Viewed 63 times
0
-
One way to do it is to take a comma-separated string as an input, and then split it on comma. Like python3 myprogram.py '1,2,3' – Fontanka16 Nov 15 '20 at 23:30
3 Answers
0
As far as I have understood your question, you want to make a list from the set of inputs of numbers having comma or space.
a = list(input("Enter your number: "))
b = [int(elements) for elements in a if elements not in (" ",",",'[',']')]
# Remove int if you are doing for strings
print(b)
Output:
Enter your number: [1,2,3]
[1 ,2 ,3]

Prakash Dahal
- 4,388
- 2
- 11
- 25
0
You can use list comprehension for this. It provides a concise way to create lists. The code in the square brackets asks the user for input, splits the input into a text based list, and then converts the values in the list to integers. Unfortunately, you can't create variables unless they are explicitly written in the code.
Code
x = [int(val) for val in input("Enter your numbers: ").split()]
print(x)
Input:
Enter your numbers: 1 2 3 4 5
Output:
[1, 2, 3, 4, 5]
Additional link: https://www.geeksforgeeks.org/python-get-a-list-as-input-from-user/

DapperDuck
- 2,728
- 1
- 9
- 21