[python] Converting integer to digit list

What is the quickest and cleanest way to convert an integer into a list?

For example, change 132 into [1,3,2] and 23 into [2,3]. I have a variable which is an int, and I want to be able to compare the individual digits so I thought making it into a list would be best, since I can just do int(number[0]), int(number[1]) to easily convert the list element back into int for digit operations.

This question is related to python list integer type-conversion

The answer is


you can use:

First convert the value in a string to iterate it, Them each value can be convert to a Integer value = 12345

l = [ int(item) for item in str(value) ]


num = list(str(100))
index = len(num)
while index > 0:
    index -= 1
    num[index] = int(num[index])
print(num)

It prints [1, 0, 0] object.


n = int(raw_input("n= "))

def int_to_list(n):
    l = []
    while n != 0:
        l = [n % 10] + l
        n = n // 10
    return l

print int_to_list(n)

There are already great methods already mentioned on this page, however it does seem a little obscure as to which to use. So I have added some mesurements so you can more easily decide for yourself:


A large number has been used (for overhead) 1111111111111122222222222222222333333333333333333333

Using map(int, str(num)):

import timeit

def method():
    num = 1111111111111122222222222222222333333333333333333333
    return map(int, str(num))

print(timeit.timeit("method()", setup="from __main__ import method", number=10000)

Output: 0.018631496999999997

Using list comprehension:

import timeit

def method():
    num = 1111111111111122222222222222222333333333333333333333
    return [int(x) for x in str(num)]

print(timeit.timeit("method()", setup="from __main__ import method", number=10000))

Output: 0.28403817900000006

Code taken from this answer

The results show that the first method involving inbuilt methods is much faster than list comprehension.

The "mathematical way":

import timeit

def method():
    q = 1111111111111122222222222222222333333333333333333333
    ret = []
    while q != 0:
        q, r = divmod(q, 10) # Divide by 10, see the remainder
        ret.insert(0, r) # The remainder is the first to the right digit
    return ret

print(timeit.timeit("method()", setup="from __main__ import method", number=10000))

Output: 0.38133582499999996

Code taken from this answer

The list(str(123)) method (does not provide the right output):

import timeit

def method():
    return list(str(1111111111111122222222222222222333333333333333333333))
    
print(timeit.timeit("method()", setup="from __main__ import method", number=10000))

Output: 0.028560138000000013

Code taken from this answer

The answer by Duberly González Molinari:

import timeit

def method():
    n = 1111111111111122222222222222222333333333333333333333
    l = []
    while n != 0:
        l = [n % 10] + l
        n = n // 10
    return l

print(timeit.timeit("method()", setup="from __main__ import method", number=10000))

Output: 0.37039988200000007

Code taken from this answer

Remarks:

In all cases the map(int, str(num)) is the fastest method (and is therefore probably the best method to use). List comprehension is the second fastest (but the method using map(int, str(num)) is probably the most desirable of the two.

Those that reinvent the wheel are interesting but are probably not so desirable in real use.


Use list on a number converted to string:

In [1]: [int(x) for x in list(str(123))]
Out[2]: [1, 2, 3]

If you have a string like this: '123456' and you want a list of integers like this: [1,2,3,4,5,6], use this:

>>>s = '123456'    
>>>list1 = [int(i) for i in list(s)]
>>>print(list1)

[1,2,3,4,5,6]

or if you want a list of strings like this: ['1','2','3','4','5','6'], use this:

>>>s = '123456'    
>>>list1 = list(s)
>>>print(list1)

['1','2','3','4','5','6']

Convert the integer to string first, and then use map to apply int on it:

>>> num = 132
>>> map(int, str(num))    #note, This will return a map object in python 3.
[1, 3, 2]

or using a list comprehension:

>>> [int(x) for x in str(num)]
[1, 3, 2]

The shortest and best way is already answered, but the first thing I thought of was the mathematical way, so here it is:

def intlist(n):
    q = n
    ret = []
    while q != 0:
        q, r = divmod(q, 10) # Divide by 10, see the remainder
        ret.insert(0, r) # The remainder is the first to the right digit
    return ret

print intlist(3)
print '-'
print intlist(10)
print '--'
print intlist(137)

It's just another interesting approach, you definitely don't have to use such a thing in practical use cases.


>>>list(map(int, str(number)))  #number is a given integer

It returns a list of all digits of number.


By looping it can be done the following way :)

num1= int(input('Enter the number'))
sum1 = num1 #making a alt int to store the value of the orginal so it wont be affected
y = [] #making a list 
while True:
    if(sum1==0):#checking if the number is not zero so it can break if it is
        break
    d = sum1%10 #last number of your integer is saved in d
    sum1 = int(sum1/10) #integer is now with out the last number ie.4320/10 become 432
    y.append(d) # appending the last number in the first place

y.reverse()#as last is in first , reversing the number to orginal form
print(y)

Answer becomes

Enter the number2342
[2, 3, 4, 2]

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to integer

Python: create dictionary using dict() with integer keys? How to convert datetime to integer in python Can someone explain how to append an element to an array in C programming? How to get the Power of some Integer in Swift language? python "TypeError: 'numpy.float64' object cannot be interpreted as an integer" What's the difference between integer class and numeric class in R PostgreSQL: ERROR: operator does not exist: integer = character varying C++ - how to find the length of an integer Converting binary to decimal integer output Convert floats to ints in Pandas?

Examples related to type-conversion

How can I convert a char to int in Java? pandas dataframe convert column type to string or categorical How to convert an Object {} to an Array [] of key-value pairs in JavaScript convert string to number node.js Ruby: How to convert a string to boolean Convert bytes to int? Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe SQL Server: Error converting data type nvarchar to numeric How do I convert a Python 3 byte-string variable into a regular string? Leading zeros for Int in Swift