How did I get a list as input? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How did I get a list as input?

24th Aug 2019, 8:19 AM
ranjith babloo
ranjith babloo - avatar
8 Answers
+ 2
mylist=list(input()) mylist is a list with every character in the string inputted being an element of the list.
24th Aug 2019, 8:45 AM
Ketchup🍅
Ketchup🍅 - avatar
+ 1
input() only returns a string. You can split it however using the split() function list_input = input().split(', ') This will split it by commas
24th Aug 2019, 8:33 AM
Trigger
Trigger - avatar
+ 1
input_list = eval(input()) if you type in a standard python list then input_list will really be a list for example [1, 2, 3, 4] just type this in and get the list eval() is much more than this: print(eval(“1*2*3*4”)) #24 print(eval(“12”)) #12 eval(str) executes the string as some code and returns what the string returns exec(str) executes the string as some code and returns None
24th Aug 2019, 10:38 AM
Alice
Alice - avatar
+ 1
Cbr✔[ Most active ] We can use some regular expressions to check if the user input is a list and then convert it. This may prevent dangerous code from being executed.
24th Aug 2019, 12:54 PM
Alice
Alice - avatar
+ 1
Cbr✔[ Most active ] We can first store the string in a variable and then check if it is a list, if yes then execute it. If we just use list(), what if we want a list of integers, floats, booleans or a list of lists?
24th Aug 2019, 2:13 PM
Alice
Alice - avatar
0
Cbr✔[ Most active ] input() returns string float() takes a string amd returns a float float(input()) thus returns a float because the string gets passed into float()
24th Aug 2019, 11:07 AM
Trigger
Trigger - avatar
0
Cbr✔[ Most active ] then simply list(input()) will work, and .split('')
24th Aug 2019, 12:22 PM
Trigger
Trigger - avatar