views:

357

answers:

5

How do I write the magic function below?

>>> num = 123
>>> lst = magic(num)
>>>
>>> print lst, type(lst)
[1, 2, 3], <type 'list'>
+20  A: 

You mean this?

num = 1234
lst = [int(i) for i in str(num)]
apphacker
+7  A: 

You could do this:

>>> num = 123
>>> lst = map(int, str(num))
>>> lst, type(lst)
([1, 2, 3], <type 'list'>)
John Fouhy
Note that in Python 3.0 map will return a generator, not a list.
Stephan202
+1  A: 
a = 123456
b = str(a)
c = []

for digit in b:
    c.append (int(digit))

print c
Cannonade
All that's missing is some curly braces! ;)
apphacker
<Chuckle>. You have uncovered my deep dark secret (C++). I am humbled by the other respondents sublime python-ness.
Cannonade
+4  A: 

Don't use the word list as variable name! It is a name of python built in data type.

Also, please clarify your question. If you are looking for a way to create a one-member list, do the following:

a = 123
my_list = [a]

and "pythonizing" Cannonade's answer:

a = 123
my_list = [int(d) for d in str(a)]
bgbg
I love it when I get pythonized. I feel pretty now. :P
Cannonade
+3  A: 

magic = lambda num: map(int, str(num))

then just do magic(12345) or magic(someInt) or whatever

Alex