Reversing a number using list in python

513 views Asked by At

I want to reverse a number but I get this error:

"TypeError: 'type' object is not subscriptable"

I would be grateful if you could correct my code.here is my code:

number=input("enter your number ")
num=int(number)
count=0
list1=[]
while(num!=0):
    list1.append(num%10)
    num=num//10
    count=count+1
print(list1[::-1])
k=len(list1)
after=0
for h in range(k):
    after+=int(list[h])*(10**h)
    h=-1
print(after)
4

There are 4 answers

0
Avión On BEST ANSWER

You can do it easily using list's (create, reverse, join):

''.join(map(str, list(reversed(list(str(num))))))

or just, much easier:

int(str(num)[::-1])
1
ssundarraj On

You have to cast your int into a str, reverse the string and cast it back.

This is how I'd go about it:

number = input("enter your number ")
number = int(str(number)[::-1])
2
Anurag Kanungo On

You have to use list1 in line 13.

Also, I am not sure what you want to do, you algorithm doesn't seem to be right and code is not pythonic at all.

Read about map function. If you want to do using list. (Don't use the typically C++ while loop) To break a number into list of single digits use:

list1 = map(int,str(num)) 
0
Yaswanth On

can do this as well

return eval(str(number)[::-1])

read more about extended slice methods to know more