- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference between Python iterable and iterator
An iterable can be loosely defined as an object which would generate an iterator when passed to in-built method iter(). There are a couple of conditions, for an object to be iterable, the object of the class needs to define two instance mehtod: __len__ and __getitem__. An object which fulfills these conditions when passed to method iter() would generate an iterator.
Let’s understand the below example, to understand the iterable −
string = "Tutorialspoint" for char in string: print (char)
T u t o r i a l s p o i n t
Above the code use the __getitem__(index) method which would return the element at the position specified by index.
So, our above code −
- Start with index 0
- Call string.__getitem__(index)
- IndexError raised? Stop
- The run body of the loop
- Increment index, revert back to step 2.
Iterators are defined as an object that counts interation via an iternal state variable. The variable, in this case, is NOT set to zero when the iteration crosses the last item, instead, StopIteration() is raised to indicate the end of the iteration. This also means that iterated item will be iterated once only, like in below example −
my_list = ['itemOne', 'TutorialsPoints'] iterators_of_some_list = iter(my_list) for i in iterators_of_some_list: print(i) for j in iterators_of_some_list: # doesn't work print(j) #However for k in my_list: print(k) for l in my_list: # it worked print(l)
itemOne TutorialsPoints itemOne TutorialsPoints itemOne TutorialsPoints
Above code holds true because the iter() method on the iterator returns itself (is to remember the current state). So above we have a loop kind of implementation similar to “for” to terminate it.
- Difference between Iterator and Spilt Iterator in Java.
- Convert Iterator to Iterable in Java
- Difference between Iterator and Enumeration in Java
- Difference Between Iterator and ListIterator in Java
- Difference between an Iterator and ListIterator in Java
- Difference Between Iterator and Enumeration Interface in Java
- Difference between Python and PHP.
- Difference between Python and Bash
- Difference between C and Python
- Difference Between PHP and Python
- Python Iterator Types
- PHP Iterable interface
- Iterator function in Python
- Iterator Functions in Python
- Difference between == and is operator in python.