Tomislav_St Tomislav_St - 1 year ago 104
Python Question

Input a list using Python

I have one little problem with my python knowledge (novice  ).
The thing I'm trying to do is input list of strings to variable and then I'll need to do some for looping over the list and return few strings from list.

The problem is that I don't know how to input a list to variable.

Here's a code how I tried:

x=(input('Please enter a list of strings: '))

...and then I entered
['car', 'house', 't-shirt', 'bicycle', 'images']
assuming that
will be a variable with list of strings but it's not.

Please help.

Answer Source

I am assuming you are using python 3.x. If you are trying to input a list, using input I think the data will be treated as string even though you type in ['car', 'house', 't-shirt', 'bicycle', 'images']

You can try this to convert the data to a list:

str_x = input('Please enter a list of strings: '))
x = [s.strip() for s in str_x[1:-1].split(',')]   # String to List conversion
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download