Open In App

Python | Split a list having single integer

Last Updated : 18 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a list containing single integer, the task is to split each value in the list. 

Examples: 

Input: Input = [23]
Output: Output  = [2, 3]

Input: Input = [15478]
Output: Output  = [1, 5, 4, 7, 8]

Method #1 : Using Map 

Python3




# Python code to split list containing single integer
 
# List initialization
input = [200]
 
# Using map
output = list(map(int, str(input[0])))
 
# Printing output
print(output)


Output:

[2, 0, 0]

  Method #2 : Using list comprehension 

Python3




# Python code to split list containing single integer
 
# List initialization
input = [231]
 
# Using list comprehension
output = [int(x) if x.isdigit() else x
          for z in input for x in str(z)]
 
# Printing output
print(output)


Output:

[2, 3, 1]

  Method #3 : Using Loops 

Python3




# Python code to split list containing single integer
 
# List initialization
input = [987]
 
# Converting to int
input = int(input[0])
 
# Output list initialization
output = []
 
while input>0:
    rem = input % 10
    input = int(input / 10)
    output.append(rem)
 
# Printing output
print(output)


Output:

[7, 8, 9]

Method #4 : Using string manipulation instead of integer manipulation

Step-by-step approach:

  • Initialize the input list with a single integer
  • Convert the integer to a string using the str() function
  • Use a for loop to iterate over the characters of the string
  • Convert each character back to an integer using the int() function
  • Append the integer to the output list
  • Print the output list

Below is the implementation of the above approach:

Python3




# List initialization
input = [987]
 
# Converting to string
input_str = str(input[0])
 
# Output list initialization
output = []
 
# Loop over characters of the string
for char in input_str:
    # Convert character to integer and append to output
    output.append(int(char))
 
# Printing output
print(output)


Output

[9, 8, 7]

Time complexity: O(n), where n is the number of digits in the input integer.
Auxiliary space: O(n), where n is the number of digits in the input integer. This is because we need to store the output list, which contains n integers.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads