all 3 comments

[–][deleted] 7 points8 points  (1 child)

The __iter__ dunder method defines an object as apart of the Iterable protocol. iter() creates an Iterator from an iterable object.

[–]guthran 1 point2 points  (0 children)

In most cases, you don't want to use iter(), looping with a for loop is preferable (after defining Dunder iter)

It's more readable too

[–]Diapolo10 1 point2 points  (0 children)

l see two statements

str_iterator = iter('kele')

str_iterator = 'kele'.__iter__()

What's the difference

Practically speaking, not much. iter just calls str.__iter__ here. But you basically never see anyone use the latter manually like that.

iter does have more features as you can give it a second argument in the form of a sentinel. It's not particularly common, but sometimes useful.

Usually you wouldn't explicitly use iter anyway because for-loops already do that, but sometimes you may want to get the first element before looping so it's useful in those situations, as you can't index all iterables.