Convert a number to a list of integers in Python

This tutorial will discuss about unique ways to convert a number to a list of integers in Python.

Table Of Contents

Method 1: Using List Comprehension

Convert the given number to string using str() method. Then iterate over all numeric characters of that string, and add them to a List using List Comprehension. But before adding them to list, convert each numeric character back to integer using int().

Let’s see the complete example,

num = 1459

# Convert number into a list of integers
listOfInts = [int(ch) for ch in str(num)]

print(listOfInts)

Output

[1, 4, 5, 9]

Method 2: Using map() method

Convert the given integer to string using str() method. Then apply int() function on each of the numeric character in string, using map() function. It will give us the result as a mapped object, containing all the numbers. Convert that mapped object to list.

Let’s see the complete example,

num = 1459

# Convert number into a list of integers
listOfInts = list(map(int, str(num)))

print(listOfInts)

Output

[1, 4, 5, 9]

Method 3: Using enumerate() method

Convert the given number to string using str() method. Then iterate over each character in string using enumerate() function. For each numeric character in string, it will yield a character and its index poistion. Convert each numeric character to integer using int() function, and populate them into a list.

Let’s see the complete example,

num = 1459

# Convert number into a list of integers
listOfInts = [int(ch) for index, ch in enumerate(str(num))]

print(listOfInts)

Output

[1, 4, 5, 9]

Method 4: Using for-loop

Convert the given number to string, and using a for-loop iterate over all numeric characters in that string. During the loop, convert each character to int, and store them in a List.

Let’s see the complete example,

num = 1459

listOfInts = []

# iterate over each numeric
# character in string
for ch in str(num):
    # convert numeric char to int
    # and add to list
    listOfInts.append(int(ch))

print(listOfInts)

Output

[1, 4, 5, 9]

Summary

We learned about different techniques to convert a number to a list of integers in Python. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top