[Tutor] Breaking down integers?

Orri Ganel singingxduck at gmail.com
Mon Jan 3 23:33:20 CET 2005


On Mon, 3 Jan 2005 17:17:36 -0500, kilovh <kilovh at gmail.com> wrote:
>  
> I would like to be able to take an integer, break it down into individual
> items in a list, and then put them back together. I know how to do this last
> part thanks to Orri Ganel and Guillermo Fernandex, but what about taking the
> integer apart? 

It sounds like you're looking for something like this:

' '.join(str(integer)).split()

First, you stringify the integer. Then, you separate each digit by a
space (' '.join(...)). Finally, you split the result into a list
(split()'s default separator is a space, which is why you separate the
digits with spaces).

So, for the integer 6942:

>>> num = 6942
>>> numlist = ' '.join(str(num)).split()
>>> numlist
['6', '9', '4', '2']

And then, if you want the digits to be integers, 

>>> numlist = [int(item) for item in numlist]
>>> numlist
[6, 9, 4, 2]

This uses list comprehension.  It is the equivalent of typing:

for item in numlist:
    numlist[numlist.index(item)] = int(item)

or

for i in range(len(numlist)):
    numlist[i] = int(numlist[i])

The reason the latter two methods assign on a per - entry basis, while
the first assigns the entire list, is because using a list
comprehension returns a list itself (notice the list-like notation). 
You are assigning numlist to a list whose entries are defined as
int(entry) for each entry already in numlist. One of the reasons this
works is because Python first evaluates the right side of the equals
sign, then assigns it.


HTH,
Orri

-- 
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.


More information about the Tutor mailing list