Table of Contents

Python code that takes a number & returns a list of its digits

So, for 28962 it should return [2,8,9,6,2]

 

Python code implementation without user-defined functions & classes

Code: 
#Python code that takes a number & returns a list of its digits

input_number = input("Enter the number: ")

#The easiest way is to convert any integer number to string
#String can be treated as a list
#Traverse the list and convert every element to integer
# and store in another list

c = str(input_number)

#Take an empty list
int_list = []
for i in range(len(c)):
    int_list.append(int(c[i]))


print(int_list)

 

Output: 
Enter the number: 340676
[3, 4, 0, 6, 7, 6]
Python Code Editor Online - Click to Expand

Python code implementation using function

In this code we will pass a number. We will pass the number to a function that will return a list of its digits.

Code: 
#Python code that takes a number & returns a list of its digits
#Using Function

def return_list_of_digits(number_1):
    c = str(number_1)
    int_list = []
    for i in range(len(c)):
        int_list.append(int(c[i]))
    return int_list


input_number = input("Enter the number: ")

list_of_digits = return_list_of_digits(input_number)

print(list_of_digits)

 

Output: 
Enter the number: 2095782416
[2, 0, 9, 5, 7, 8, 2, 4, 1, 6]
Python Code Editor Online - Click to Expand

Python code implementation using Classes

In this code, we will take a number. We will implement a class that contain a function to convert the number into a list of its digits. We will create an object and will call the function using object.function(), the will return a list of its digits.

Code: 
#Python code that takes a number & returns a list of its digits
#Using Classes

class List_of_Digits(object):
    def return_list_of_digits(self, number_1):
        self.number_1 = number_1
        c = str(self.number_1)
        int_list = []
        for i in range(len(c)):
            int_list.append(int(c[i]))
        return int_list


input_number = input("Enter the number: ")

#Create object
object_digit = List_of_Digits()

list_of_digits = object_digit.return_list_of_digits(input_number)

print(list_of_digits)

 

Output: 
Enter the number: 34581304893
[3, 4, 5, 8, 1, 3, 0, 4, 8, 9, 3]
Python Code Editor Online - Click to Expand

 

Enjoy Python Code By Pythonbaba 🙂