Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split three-digit integer to three-item list of each digit in Python

Tags:

python

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.

like image 705
Martin Bean Avatar asked Sep 02 '11 10:09

Martin Bean


People also ask

How do you split a number into a list of digits in Python?

To split an integer into digits:Use the str() class to convert the integer to a string. Use a for loop to iterate over the string. Use the int() class to convert each substring to an integer and append them to a list.


1 Answers

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]
like image 177
Frédéric Hamidi Avatar answered Sep 27 '22 20:09

Frédéric Hamidi