Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

This is my function:

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

Output:

Input: 1234

output: [1234, 123, 12, 1]

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

1 Answer

0 votes
by (36.8k points)

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

1-Liner using the 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]

Learn data science with python course to improve your technical knowledge.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...