-2

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)
hardillb
  • 54,545
  • 11
  • 67
  • 105

4 Answers4

1

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])
Avión
  • 7,963
  • 11
  • 64
  • 105
0

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])
ssundarraj
  • 809
  • 7
  • 16
0

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)) 
Anurag Kanungo
  • 354
  • 3
  • 5
  • *"list is a python keyword"* - not strictly speaking, you **can** use `list` for your own object, although it's discouraged. The OP's problem is simply that they haven't assigned a list to it - if they'd used a different name, they would have had a `NameError` not a `TypeError`. – jonrsharpe Jun 15 '15 at 10:05
  • Thanks for your help and guides.I read about map function and found out that elementary problem solving methods and not coding Pythonicly, costs me a lot of time and coding in this way is not efficient at all.I am at the beginning of programming python. I use advanced programmer's guides to be a efficient and well informed. – Sobhan Taheri Jun 16 '15 at 09:08
0

can do this as well

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

read more about extended slice methods to know more

Yaswanth
  • 113
  • 1
  • 1
  • 7