Table of content

## How to convert a number to a list in python?

Consider a number num = 32456. The variable num when converted to a list results in [3, 2, 4, 5, 6]. This article discusses several approaches to convert a number to a list in python.

### Converting a number to a list by using the for loop

Consider a number num = 987456. The num is converted to string data type using str() function so that we can iterate over the digits in variable num. In each iteration, the digit is converted to integer data type using the int() function and is appended to the list.

``````num = 987456
print("num: ", num)
list_1 = []
for i in str(num):
list_1.append(int(i))
print("list_1: ", list_1)``````

The above code returns the output as,

``````num:  987456
list_1:  [9, 8, 7, 4, 5, 6]``````

### Converting a number to a list by using the map() function

The map() function has two parameters, a function and an iterable. It passes each data item of the iterable as an argument to the function. The syntax for the map() function is given below.

``````#syntax:
map(function, iterable)``````

Consider a number num = 987456. The num is converted to string data type using the str() function. The map(int, str(num)), takes each digit of the string and passes it to the int function, and returns an iterator. The list() constructor converts the iterator to a list-type object.

``````num = 987456
print("num: ", num)
list_1 = list(map(int, str(num)))
print("list_1: ", list_1)``````

The above code returns the output as

``````num:  987456
list_1:  [9, 8, 7, 4, 5, 6]``````

### Converting a number to a list by using split() + map()

Consider a number num = 987456. The num is converted to string data type using the str() function and is stored in a variable string_1. The split() method breaks the string into a list of strings and stores in list_1 = ['9', '8', '7', '4', '5', '6']. The map() function passes each data item of the list_1 as an argument to the function int.

The list() constructor then converts the map object to a list of integers and returns a list of numbers [9, 8, 7, 4, 5, 6].

``````num = 987456
print("num: ", num)
string_1 = str(num)
list_1 = list(string_1)
print("List of strings: ", list_1)
list_2 = list(map(int, list_1))
print("list_2: ", list_2)``````

Output

``````num:  987456
List of strings:  ['9', '8', '7', '4', '5', '6']
list_2:  [9, 8, 7, 4, 5, 6]``````
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions