-1

I have a list that looks like this:

mylist = ['1,2,3']

It is a list of one string. I want to convert this to a list of integers like:

mylist = [1,2,3]

I tried [int(x) for x in mylist.split(',')] but it doesn't work. Can someone please help? Thanks in advance.

Tania
  • 1,855
  • 1
  • 15
  • 38
  • Have a look at: http://stackoverflow.com/questions/6378889/how-to-convert-a-string-list-into-an-integer-in-python – bish May 13 '15 at 05:10
  • Hint ! str is itself a list and hence mylist is list of list (speaking on a broader term) . So you need to dissect two list's not one! – therealprashant May 13 '15 at 05:13

2 Answers2

3

Using list comprehension. split is a string method

[int(j)  for i in  mylist for j in i.split(',')]
styvane
  • 59,869
  • 19
  • 150
  • 156
1

The reason your code doesn't work is that your list only contains one item - "1,2,3". Split the first (and only) item in the list on comma, then map int to the items you get:

mylist = ['1,2,3']
print map(int, mylist[0].split(","))

Prints

[1, 2, 3]

If you have more than one item in your list, you can do

print map(int, [sub for item in mylist for sub in item.split(",")])
EvenLisle
  • 4,672
  • 3
  • 24
  • 47