Home  >  Article  >  Backend Development  >  How to Extract Digits from an Integer into a List in Python?

How to Extract Digits from an Integer into a List in Python?

Barbara Streisand
Barbara StreisandOriginal
2024-11-06 04:56:02159browse

How to Extract Digits from an Integer into a List in Python?

Extracting Digits from an Integer into a List

When working with integers in Python, it can be useful to decompose them into individual digits for various operations. This article demonstrates how to convert an integer, such as 12345, into a numeric list: [1, 2, 3, 4, 5].

To achieve this, we must convert the integer to a string to gain access to its individual characters. Subsequently, we iterate over each character and convert it back to an integer using a list comprehension.

<code class="python">input_integer = 12345
split_digits = [int(i) for i in str(input_integer)]

print(split_digits)</code>

Output:

[1, 2, 3, 4, 5]

This approach effectively splits the integer into its constituent digits, creating a list of integers that can be utilized for further processing or calculations.

The above is the detailed content of How to Extract Digits from an Integer into a List in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn