l=[20,30,40]
r = [[int(c) for c in str(e)] for e in l]
print(r)
[[2, 0], [3, 0], [4, 0]]
As you see, the trick is to pass each element ( e
) of the list l
to string, then iterate through each of the characters ( c
) of that string and convert it to int
. The syntax of list comprehensions allows you to express all of it in a single line. If you prefer more the syntax of loops it would be like that (much more complicated in my opinion):
r = []
for e in l:
aux = []
for c in str(e):
aux.append(int(c))
r.append(aux)
print(r)
The product
And answering your "true" question, calculate the product of the digits of each number, we have two approaches:
Use functional programming to operate on each item in the list r
(which is itself a sub-list), reducing the sub-list to a single data (using functools.reduce()
, and applying the operator of multiplication to all of them).
Use a for loop for the same thing.
Functional programming hides loops, allowing shorter programs, but sometimes more difficult to read. In the case of the function functools.reduce()
is one of those cases in which, to make the program more compact, it loses legibility (in fact Guido himself, creator of python, discourages it). It would be like this:
from functools import reduce
from operator import mul
l = [123, 35, 11111]
r = [[int(c) for c in str(n)] for n in l]
p = [reduce(mul, sublist) for sublist in r]
print(p)
[6, 15, 1]
In this case a solution with loops is, for my taste, more readable:
l = [123, 35, 11111]
for e in l:
product = 1
for digit in str(e):
product *= int(digit)
print(product)
6
15
1
Note that both the functional version and the loop version serve data of any length.