-3

How to Filter the palindrome numbers in the given tuple and save it in the tuple ?

My code :

w = (10,11,12,21,22,101,123,111,152)

for i in w:
    if i[:]==i[-1:]:
        print(i)

Error : TypeError                                 Traceback (most recent call last)
<ipython-input-143-b2b3cfdef377> in <module>
      7 
      8 for i in w:
----> 9     if i[:]==i[-1:]:
     10         print(i)

TypeError: 'int' object is not subscriptable
BioGeek
  • 21,897
  • 23
  • 83
  • 145

3 Answers3

1

Convert your integer to a string. Also, you weren't using the inverse slicing of the string correctly

w = (10,11,12,21,22,101,123,111,152)

for i in w:
    if str(i) == str(i)[::-1]:
        print(i)

Output:

11
22
101
111

You also mention that you want to save the result in a tuple. Use a generator expression for that:

tuple(i for i in w if str(i) == str(i)[::-1])

Output:

(11, 22, 101, 111)
BioGeek
  • 21,897
  • 23
  • 83
  • 145
1

You cannot use indices for integer values.

  1. i[:] does not work.
  2. str(i)[:] works.

Also str(i)[:] is the same thing with str(i) and str(i)[-1:] only takes the last digit of the number.

If you want to get the number reversed you have to use str(i)[::-1].

This should work just fine :

w = tuple(i for i in w if str(i) == str(i)[::-1])
print(w)

Check this for a better understanding of the slicing operator:

0

Try This Code:

w = (10,11,12,21,22,101,123,111,152)
for i in w:
    if str(i)[:]==str(i)[::-1]: 
        print(i)