9

I'm new to Python. What I want to do is take a three-digit integer like 634, and split it so it becomes a three-item list, i.e.

digits = [ 6, 3, 4 ]

Any help in this would be much appreciated.

Martin Bean
  • 38,379
  • 25
  • 128
  • 201
  • 2
    What did you try? Please include code you tried that didn't work. – S.Lott Sep 02 '11 at 10:19
  • I don't know where to start. As I say, I'm new to Python. – Martin Bean Sep 02 '11 at 10:20
  • 1
    New is not excuse for not reading the tutorial and poking around to try something. Also new is no excuse for not searching. The tutorials are really good and you'll learn more from a tutorial than you will by asking questions here. – S.Lott Sep 02 '11 at 10:22
  • @martin Here's the [tutorial](http://tinyurl.com/lcxa3t). – Keith Sep 02 '11 at 10:26
  • 2
    I've poked around in the tutorial and it wasn't immediately apparent to me, coming from a PHP background. Sorry if you think this was a 'n00b' question and beneath you to spend time answering. It was no different to the numerous, "How do you do x in language y?" questions that swathe this site I feel. – Martin Bean Sep 02 '11 at 10:51
  • @Martin Bean: It's not beneath our time. Asking questions like this is a waste of your time. Don't "poke around". Do the entire tutorial. It takes *less* time than wading through answers here. – S.Lott Sep 02 '11 at 12:48
  • 1
    Not really: I got the answer I needed in a couple of minutes, thanks to fantastic members of this community. – Martin Bean Sep 02 '11 at 14:24
  • @Martin Bean: " I got the answer I needed in a couple of minutes." That's funny. The level of understanding you got was probably far below what you would have gotten from the tutorial. Or. You're able to glean huge amounts of information from small (and possibly misleading) answers. If you're able to get a good understanding of Python from this question, I apologize for suggesting you do what everyone else does to learn Python. – S.Lott Sep 02 '11 at 15:45
  • Unfortunately, I didn't have the time to leisurely read over the Python documentation; instead I knew the Stack Overflow community would give me the answer to the specific problem I was facing in order to get on with my job. Python I intend to learn, just like "everyone else", by reading the documentation. Sorry for the confusion. – Martin Bean Sep 02 '11 at 19:08

8 Answers8

20

You can convert the number to a string, then iterate over the string and convert each character back to an integer:

>>> [int(char) for char in str(634)]
[6, 3, 4]

Or, as @eph rightfully points out below, use map():

>>> map(int, str(634))        # Python 2
[6, 3, 4]

>>> list(map(int, str(634)))  # Python 3
[6, 3, 4]
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
  • 3
    More simple: `map(int, str(634))` – eph Sep 02 '11 at 10:27
  • 2
    @eph, that's indeed simpler, but in Python 3 `map()` [returns an iterator](http://diveintopython3.org/porting-code-to-python-3-with-2to3.html#map), so an extra call to `list()` is required. – Frédéric Hamidi Sep 02 '11 at 10:31
  • Great answer. Just wondering but how would you do this in reverse? Say you have the list from your example [6, 3, 4] how do you go backwards and create the integer 634 from the list? Thanks for your help. – EazyC Apr 17 '16 at 09:36
  • 1
    @EazyC, you could convert the integers to strings, join the strings and convert the result back to an integer. Something like `int("".join(map(str, [6, 3, 4])))`. – Frédéric Hamidi Apr 17 '16 at 10:04
  • @FrédéricHamidi Thank you that worked very well! Much appreciated. – EazyC Apr 17 '16 at 10:57
8

Using str() is a bit lazy. Quite a lot slower than using math. Using a while loop would be faster still

In [1]: n = 634

In [2]: timeit [int(i) for i in str(n)]
100000 loops, best of 3: 5.3 us per loop

In [3]: timeit map(int, str(n))
100000 loops, best of 3: 5.32 us per loop

In [4]: import math

In [5]: timeit [n / 10 ** i % 10 for i in range(int(math.log(n, 10)), -1, -1)]
100000 loops, best of 3: 3.69 us per loop

If you know it's exactly 3 digits, you can do it much faster

In [6]: timeit [n / 100, n / 10 % 10, n % 10]
1000000 loops, best of 3: 672 ns per loop
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • oh man that's cool!! i was just trying to do it without string conversion, i'd gotten as far as `[n % pow(10,i+1) / pow(10,i) for i in reversed(xrange(3))]` and was just trying to figure out how to get `len(n)` with maths when your much more elegant answer popped up – wim Sep 02 '11 at 11:16
  • @Liesmith, not sure which part of the answer you are referring to. You need to use `//` in Python3 instead of `/` for truncating division – John La Rooy Oct 04 '14 at 10:48
  • @gnibbler, I'd tried that before posting my previous comment, using `[n//10**i%10 for i in range(int(math.log(n,10)),-1,-1)]` as the function "getDigs(n)". I just tried to recreate the problem, but now it works perfectly. I have no idea why it gave me such odd results previously, so I deleted my previous comment to avoid confusing anyone else who stumbles across that in the future. Thanks for the very elegant solution. – Liesmith Oct 06 '14 at 22:44
5

Convert to string, treat string as a list and convert back to int:

In [5]: input = 634
In [6]: digits =[int(i) for i in str(input)]
In [7]: print digits
[6, 3, 4]
KillianDS
  • 16,936
  • 4
  • 61
  • 70
3

Alternatively you can do this with the decimal module:

>>> from decimal import Decimal
>>> Decimal(123).as_tuple()
DecimalTuple(sign=0, digits=(1, 2, 3), exponent=0)
>>> Decimal(123).as_tuple().digits
(1, 2, 3)

...which also works with real numbers...

>>> Decimal(1.1).as_tuple()
DecimalTuple(sign=0, digits=(1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 1, 7, 8, 4, 1, 9, 7, 0, 0, 1, 2, 5, 2, 3, 2, 3, 3, 8, 9, 0, 5, 3, 3, 4, 4, 7, 2, 6, 5, 6, 2, 5), exponent=-51)
>>> Decimal('1.1').as_tuple()
DecimalTuple(sign=0, digits=(1, 1), exponent=-1)
richardw
  • 728
  • 5
  • 9
  • 1
    +1 for a different approach. Unfortunately in my tests this took about twice as long as the map(int, str(n)) method. – Sean Feb 13 '13 at 17:03
1

Like this:

Python2> i = 634
Python2> digits = [int(d) for d in list(str(i))]
Python2> digits
[6, 3, 4]

This turns the int into a string, breaks the characters into a list, and maps the list back into ints (using a list comprehension).

Keith
  • 42,110
  • 11
  • 57
  • 76
1

To do this without conversion to a string (and without cheating by using log to see how many digits there will be), use repeated calls to divmod:

>>> digits = []
>>> value = 634
>>> while value: value,b = divmod(value,10); digits.insert(0,b)
...
>>> digits
[6, 3, 4]
PaulMcG
  • 62,419
  • 16
  • 94
  • 130
0

You can use this function to turn any number to a list of decimal digits:

def todigits(n):
    return map(int, list(str(n)))

Or this one does the opposite:

def fromdigits(lst):
    return int("".join(map(str, lst)))
Enrique Pérez Herrero
  • 3,699
  • 2
  • 32
  • 33
0
num = 153

while num > 0:
    digit = num % 10
    print(digit)
    num //= 10