Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for What is Iterable,iterator in Python?
Adarsh Rawat
Adarsh Rawat

Posted on • Edited on

     

What is Iterable,iterator in Python?

First , we have to understand what is itertors, and why it is used?

Iterator :-

An iterator is an object that contains a countable number of values, in simple words an iterators stores numbers of values,
through which we can iterated upon (traversing over the values).

In Python an iterator is an object which implements the iterator protocol, which consist of the methodsiter() andnext().

Iteratble :-

objects like (strings, list, tuple, sets, dict) are all iterable (container of values).

Iterator :-

each of above iterable has aniter() method which can be used to get iterator of that particular object i.e, for list we get list_iterator object , for tuple we get tuple_iterator and so on...
let us understand with an example

>>> student_name = ['ram','shyam','john','harry','ravi']>>> student_iter = iter(student_name)>>> student_iter<list_iterator object at 0x000001E7C37E1F30> # list_iterator object>>>>>> print(next(student_iter))ram>>> print(next(student_iter))shyam>>> print(next(student_iter))john>>> print(next(student_iter))harry>>> print(next(student_iter))ravi
Enter fullscreen modeExit fullscreen mode

Using thenext(iterable) we can move over elements in the iterator, Remeber on important in iterator object does not have any exception handler , so if we try to call next() ,when we are on the last element, it will throw anStopIteration Exception
the last element in the list is 'ravi' and we are currently on ravi, then let's see what happen what happen if we callnext().

>>> print(next(student_iter))ravi>>> print(next(student_iter))Traceback (most recent call last):  File "<stdin>", line 1, in <module>StopIteration>>>
Enter fullscreen modeExit fullscreen mode

There are mutiple ways to handle thisStopIteration Exception
let's see each one of them.

1. We can use try and except block
>>> next(student_iter)'ravi'>>> try:...     print(next(student_iter))... except StopIteration:...     print("StopIteration Exception Handled")...StopIteration Exception Handled>>>
Enter fullscreen modeExit fullscreen mode

Here, we have handled the exception use try and except block,
it is still a solution to the block , but at the same time , every time we have to use extra lines of code whenever we usenext() on the last element.

2. Using for loop
>>> for student in student_iter:...     print(student)...ramshyamjohnharryravi>>>
Enter fullscreen modeExit fullscreen mode

for loop internally handles theStopIteration Excetion whenever itnext() called on the last element.

  1. By Passing Second Argument innext(iterable,sentinel)you can think sentinel as the default value return whenever *next * called on the last element.
>>> student_name = ['ram','shyam','john','harry','ravi']>>> student_iter = iter(student_name)>>> next(student_iter,None)'ram'>>> next(student_iter,None)'shyam'>>> next(student_iter,None)'john'>>> next(student_iter,None)'harry'>>> next(student_iter,None)'ravi'>>> next(student_iter,None)>>>
Enter fullscreen modeExit fullscreen mode

You can see that ,we passed second argument asNone , so when we called next on the last element, it does not throw theStopIteration Excetion instead it return thesentinel (default value). In this way we don't don't have to write extra lines of code , only have to pass the second argument.

That's it for now,
i think it would to enough for now,
I will cover some advance topics about iterator in python in the
next article ,*(types of iterators in python, and which is the most optimal one to use).

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

An aspiring software developer
  • Joined

More fromAdarsh Rawat

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp