Python | Split a list having single integer
Last Updated :
18 Apr, 2023
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
input = [ 200 ]
output = list ( map ( int , str ( input [ 0 ])))
print (output)
|
Method #2 : Using list comprehension
Python3
input = [ 231 ]
output = [ int (x) if x.isdigit() else x
for z in input for x in str (z)]
print (output)
|
Method #3 : Using Loops
Python3
input = [ 987 ]
input = int ( input [ 0 ])
output = []
while input > 0 :
rem = input % 10
input = int ( input / 10 )
output.append(rem)
print (output)
|
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
input = [ 987 ]
input_str = str ( input [ 0 ])
output = []
for char in input_str:
output.append( int (char))
print (output)
|
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.
Share your thoughts in the comments
Please Login to comment...