[Tutor] string to list

Steven D'Aprano steve at pearwood.info
Wed Feb 10 15:13:39 CET 2010


On Thu, 11 Feb 2010 12:32:52 am Owain Clarke wrote:

> My son was doing a statistics project in which he had to sort some
> data by either one of two sets of numbers, representing armspan and
> height of a group of children - a boring and painstaking job.  I came
> across this piece of code:-
>
> li=[[2,6],[1,3],[5,4]]  # would also work with li=[(2,6),(1,3),(5,4)]
> li.sort(key=lambda x:x[1] )
> print li
>
> It occurred to me that I could adapt this so that he could input his
> data at the command line and then sort by x:x[0] or x:x[1].  And I
> have not discovered a way of inputting a list, only strings or
> various number types.

Which command line do you mean? If you are talking about the Python 
interactive interpreter, then you can input either lists or strings:

>>> li = [1, 2, 3]  # a list
>>> li = "[1, 2, 3]"  # a string

If you mean the external shell (say, "bash" under Linux or the DOS 
command line in Windows, or similar) then you can only input strings -- 
everything is a string in such shells.

There are two ways to convert such strings to lists: the easy, unsafe 
way; or the slightly more difficult but safer way. Think of it like The 
Force, where the Dark Side is simpler and more attractive but 
ultimately more dangerous :)

First, the easy way. If you absolutely trust the source of the data, 
then you can use the eval function:

>>> s = "[1, 2, 3]"  # quote marks make it a string
>>> li = eval(s)

The interpreter will read the string s as a Python expression, and do 
whatever it says. In this example, it says "make a list with the 
numbers 1, 2 and 3 in it". But it could say *anything*, like "erase the 
hard disk", and Python would dutifully do what it is told. This is why 
eval is easy and fast but dangerous, and you must absolutely trust the 
source of the string.

Alternatively, you could do this:

>>> s = "1 2 3 4"  # numbers separated by spaces
>>> li = s.split()  # li now contains the strings "1", "2" etc.
>>> li = map(int, li)  # convert the strings to actual ints
>>> print li
[1, 2, 3, 4]


Naturally the string s would come from the shell, otherwise there is no 
point! If you are typing the data directly into the Python interpreter, 
you would enter it directly as a list and not a string.

Hope this helps,



-- 
Steven D'Aprano


More information about the Tutor mailing list