How to split a list that has ONLY ONE integer value in Python?

Question:

I want to split a value in a list and make it two values.

arr = [10]

The array should turn in to:

arr = [1,0]
Asked By: User

||

Answers:

Use list comprehension with two iterations:

>>> [int(x) if x.isdigit() else x for y in arr for x in str(y)]
[1, 0]
>>> 
Answered By: U12-Forward

In order to split up an integer in the format like this, you can use str() to
make the integer into its parts.

You would need to do this on just the variable not, the list.
So

num = arr[0]

and then turn this into a string

string = str(num)

which you can turn into an list with list()

And then you would turn the multiple strings back into numbers with int()

So all together:

>>> arr = [10]
>>> num = arr[0]
>>> string = str(num)
>>> string_arr = list(string)
>>> arr = list(map(int, string_arr))
>>> arr
[1,0]

Or simplified down instead of using intermediate variables.

>>> arr = [10]
>>> arr = list(map(int, str(arr[0])))
>>> arr
[1,0]
Answered By: The Matt

You can use either a list comprehension:

[int(digit) for digit in str(arr[0])]

Or list(map()):

list(map(int, str(arr[0])))

For the most efficient solution, don’t convert to a string; instead, use basic math operations:

import math

[arr[0] // 10 ** n % 10 for n in reversed(range(int(math.log10(arr[0])) + 1))]
Answered By: iz_

You can use a while loop to keep dividing the given integer by 10 and yielding the remainder until the quotient becomes 0, and then reverse the resulting list to obtain the desired list:

def split_int(i):
    while True:
        i, r = divmod(i, 10)
        yield r
        if not i:
            break

so that list(split_int(arr[0]))[::-1] returns:

[1, 0]
Answered By: blhsing

It can be solved by using map, list, converting to string, list comprehension.

If your list has only one value.

Python 2

arr = [10]
arr = map(int,str(arr[0]))

Python 3

arr = [10]
arr = list(map(int, str(arr[0])))

Both for python 2 and 3

arr = [10]
arr_str=list(str(arr[0]))
arr = [int(x) for x in arr_str]

one Liner

arr = [10]
arr = [int(x) for x in list(str(arr[0]))]
Answered By: bkawan
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.