What is the easiest or most elegant way to let the user input a list in a console program?

A list with the brackets and commas?

The easiest way is also taboo:

>>> eval(raw_input("Enter a list: "))
Enter a list: [1,2,3]
[1, 2, 3]

IMO, eval() should almost never be used for the simple reason that it allows the user to type ANYTHING. As in

>>> eval(raw_input("Enter a list: "))
Enter a list: os.rmdir("C:\")

OOPS.

which WILL execute if the appropriate permissions are there.

So instead, we have to do it by hand:

def get_list():
	mylist = raw_input("Enter a list: ").strip()
	if mylist.startswith('['):
		mylist = mylist[1:]
	else:
		print "ERROR!"
		return None
	if mylist.endswith(']'):
		mylist = mylist[:-1]
	else:
		print "ERROR!"
		return None
	return mylist.split(",")

>>> get_list()
Enter a list: [1,2,3,4]
['1', '2', '3', '4']

But note: this will return strings!

A possible compromise might be this:

>>> def get_list2():
	mylist = raw_input("Enter a list: ").strip()
	if not mylist.startswith('[') or not mylist.endswith(']'):
		print "ERROR!"
		return None
	return eval(mylist)

>>> get_list2()
Enter a list: [1,2,3,4]
[1, 2, 3, 4]
>>>

with the error checking in place, I think eval() is safe here.

Jeff

Thanks Jeff, I am learning a lot. I will test drive your code and let you know.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.