-2

As i know we can not iterate int value while we can iterate strings in python.
I want to know exact reason why it is. ?

#Example
>>> p = 12
>>> for i in p:
...     print i
... 
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'int' object is not iterable
>>> p = "abctest"
>>> for i in p:
...     print i
... 
a
b
c
t
e
s
t
>>> 

Edited : I need exact reason.Please do not say that you can use range , loop.

Prashant Gaur
  • 9,540
  • 10
  • 49
  • 71
  • Uhm, because a string is a sequence of characters? What do you expect an integer to iterate as? Digits do not form a sequence. Iterating over `12` makes no sense as `1` and `2` have a different *meaning* as integers, while `'a'`, `'b'` and `'c'` still are the same characters they were in the larger string. – Martijn Pieters Dec 03 '13 at 11:01
  • why downvotes ?? i am just asking my confusions .. – Prashant Gaur Dec 03 '13 at 11:04
  • I didn't downvote, but I suppose that it's because anyone who've read at least one book about python would never raise such question, which means that this question doesn't show any research effort. – aga Dec 03 '13 at 11:06
  • Actually i was missing exact reason behind it. lot of books are telling int is not iterable and we can iterate strings into python.again i am getting answers like you can use range and other .i know there stuff. – Prashant Gaur Dec 03 '13 at 11:08
  • @aga .. let me know if i wrong ..i am thinking that python is doing indexing for string while for int there is no indexing.that's why we can't iterate int object. – Prashant Gaur Dec 03 '13 at 11:13
  • If you _could_ iterate over an int, what result would you expect to see?? – DNA Dec 03 '13 at 11:28
  • i am not saying i could iterate .i just want to what is there internally which is not allowing a int to iterate ,while we can iterate sting – Prashant Gaur Dec 03 '13 at 11:31
  • 1
    What result would you expect when you could iterate over `16`? And what would you expect for `0x10`? – Matthias Dec 03 '13 at 11:56
  • @Matthias i want to know why i can't iterate over 16 ??while i can iterate '16' ???? – Prashant Gaur Dec 03 '13 at 12:06
  • 2
    `16` and `0x10` are same value. So what should the reult be? – Matthias Dec 03 '13 at 12:08
  • 1
    ....The actual answer is "Uh, they decided that ints had no reason to be iterable". See [PEP 276](https://www.python.org/dev/peps/pep-0276/) – NightShadeQueen Jul 12 '15 at 17:18

7 Answers7

3

Finally i found correct answer.

Reason:

objects which are having __iter__ they are iterable.
and we can see

>>> dir(16)
['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']
>>> 

there is no __iter__ so int is not iterable .
We can check for other types.

hasattr(["a"], '__iter__')
True
hasattr(("a",), '__iter__')
True
hasattr(u"12", '__iter__')
False

for string there is no _iter_ so how can we say string is Iterable ??? Explanation :
string is having __getitem__

>>> dir('1')
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>>

We can found __getitem__ so we can say string is iterable.
The iter built-in checks for the __iter__ method and in case of strings the __getitem__ method

Prashant Gaur
  • 9,540
  • 10
  • 49
  • 71
2

A string is a list of characters. An int is not iterable.

Are you thinking about printing the numbers from 0 to 11

for i in range(12):
    print(i)

or printing the digits

for digit in str(12):
    print(digit)

Also,

>>> list('hello')
['h', 'e', 'l', 'l', 'o']
>>> list(12)
TypeError: 'int' object is not iterable
IceArdor
  • 1,961
  • 19
  • 20
  • Yes. You may convert the int to a string representation of a given base and iterate on that one if you need the int digit by digit. – Pierre Arlaud Dec 03 '13 at 11:03
1

Strings are just lists of characters. Int is just integer value. I can't imagine how to iterate over integer value.

If you want to iterate for example from 0 to n you can do

n = 10
for i in range(n):
    print i
Deck
  • 1,969
  • 4
  • 20
  • 41
1

You are meant to use range(p), for the integers that go from 0 to p, now that's iterable, because that is a range of numbers, not a number.

You are precisely meant to do:

p = 12
for i in range(p):
    print(i)

If you really want to iterate a number you can use this:

iterable = '{0:064b}'.format

So you can do:

p = 12
for i in iterable(p):
    print(i)

PD: correct reason why you cannot iterate over an integer is because it is not iterable. If you are interested on finding which kind of things are iterable and why then you should check the question: "In Python, how do I determine if an object is iterable?". Try to run dir("16") and dir(16).

Community
  • 1
  • 1
Trylks
  • 1,458
  • 2
  • 18
  • 31
1
  1. In Python all strings are sequences of Unicode characters. There is no such thing as a Python string encoded in UTF-8, or a Python string encoded as CP-1252.
  2. str is sequence of character so we can iterate while int is a unique number. That's why we can't iterate over an int object.
Asocia
  • 5,935
  • 2
  • 21
  • 46
Mairaj Khan
  • 369
  • 3
  • 13
1

What you propose is PEP-276, which was rejected because

This PEP was rejected on 17 June 2005 with a note to python-dev.

Much of the original need was met by the enumerate() function which was accepted for Python 2.3.

Also, the proposal both allowed and encouraged misuses such as:

>>> for i in 3: print i

0

1

2

Likewise, it was not helpful that the proposal would disable the syntax error in statements like:

x, = 1

Community
  • 1
  • 1
NightShadeQueen
  • 3,284
  • 3
  • 24
  • 37
0

Rephrased: "What property of the str class makes it iterable?"

Since you answered your own question (__getitem__), I upvoted. (Try repr(str.__getitem__)

See also: What's the difference between __iter__ and __getitem__?

https://docs.python.org/2/glossary.html#term-iterable

Community
  • 1
  • 1
Aaron West
  • 187
  • 2
  • 5