Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Convert number to list of integers in Python
Converting a number to a list of its individual digits is a common task in Python programming. This article explores two efficient approaches: list comprehension and the map() function with str().
Using List Comprehension
List comprehension provides a concise way to convert each digit by first converting the number to a string, then iterating through each character and converting it back to an integer ?
Example
number = 1342
# Given number
print("Given number:", number)
# Convert to list of digits using list comprehension
digits_list = [int(digit) for digit in str(number)]
# Result
print("List of digits:", digits_list)
The output of the above code is ?
Given number: 1342 List of digits: [1, 3, 4, 2]
Using map() and str()
The map() function applies the int() function to each character in the string representation of the number, creating an efficient solution ?
Example
number = 1342
# Given number
print("Given number:", number)
# Convert to list of digits using map()
digits_list = list(map(int, str(number)))
# Result
print("List of digits:", digits_list)
The output of the above code is ?
Given number: 1342 List of digits: [1, 3, 4, 2]
Handling Negative Numbers
Both methods work with negative numbers, but they include the minus sign. Here's how to handle negative numbers ?
negative_number = -1342
# Method 1: Using absolute value
digits_list1 = [int(digit) for digit in str(abs(negative_number))]
print("Using abs():", digits_list1)
# Method 2: Remove minus sign first
digits_list2 = [int(digit) for digit in str(negative_number) if digit != '-']
print("Filtering minus:", digits_list2)
Using abs(): [1, 3, 4, 2] Filtering minus: [1, 3, 4, 2]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| List Comprehension | High | Good | Simple, readable code |
| map() with str() | Medium | Slightly better | Functional programming style |
Conclusion
Both list comprehension and map() effectively convert numbers to digit lists. Choose list comprehension for readability or map() for slightly better performance with large numbers.
