Generate sub numbers from number (remove last number each time)

Viewed 41
def sub(number):
tmp = []
tmp.append(number)
while len(str(number)) > 1:
    tmp.append(int(str(number)[:-1]))
    number = int(str(number)[:-1])
return tmp

In this function I try to make this output, something like this:

Input: 1234
output: [1234, 123, 12, 1]

Now my question is there any more efficient way to do this in python?

1 Answers

You can divide by 10, 10**2, 10**3 and so on and keep the integer part.

See Floor Division (//)

1-Liner using list comprehension

[1234//10**i for i in range(len(str(1234)))]

Or

ans = [] 
for i in range(len(str(1234))):
    ans.append(1234//10**i )

Output:

[1234, 123, 12, 1]
Related