Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why do python strings not have __iter__ function?

Tags:

How is it that we can iterate over python strings when strings don't have an __iter__ function?

$ python Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)  [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> "asdf".__iter__ Traceback (most recent call last):   File "<stdin>", line 1, in <module> AttributeError: 'str' object has no attribute '__iter__' >>> it = iter("asdf")       >>> it <iterator object at 0xb736f5ac> >>>  

And more importantly (however strings are iterated over), why do python strings not follow the same convention as everything else. Particularly when the Python docs say that the __iter__ function is needed http://docs.python.org/library/functions.html#iter ?

like image 374
Alexander Bird Avatar asked Feb 25 '11 03:02

Alexander Bird


People also ask

What is__ iter__ Python?

The __iter__() function returns an iterator for the given object (array, set, tuple, etc. or custom objects). It creates an object that can be accessed one element at a time using __next__() function, which generally comes in handy when dealing with loops. Syntax : iter(object) iter(callable, sentinel)

What is the alternative if the __ ITER __ method is not defined in a custom class to make it iterable?

1) An alternative way to make an iterable is to supply a __getitem__() method that accepts consecutive indices and raises IndexError when complete. This is how str objects iterated in Python 2.

Are lists iterables Python?

An object is called iterable if we can get an iterator from it. Most built-in containers in Python like: list, tuple, string etc. are iterables.

What does the built in Python function ITER () do?

python iter() method returns the iterator object, it is used to convert an iterable to the iterator. Parameters : obj : Object which has to be converted to iterable ( usually an iterator ). sentinel : value used to represent end of sequence.


1 Answers

From your link:

or it must support the sequence protocol (the __getitem__() method with integer arguments starting at 0).

In [1]: 'foo'.__getitem__(0) Out[1]: 'f' 
like image 101
nmichaels Avatar answered Oct 06 '22 17:10

nmichaels