Difference between iterables and iterators in Python

Iterables

  1. iterables is an object over which we can iterate using loops.
  2. In other words, any object over which we can perform iteration and access it’s elements one by one is known as iterable.
  3. objects such as lists, tuples, sets, strings, dictionaries are called iterables.
  4. iterables support iter() function.

Iterators

  1. iterator is generated when the iterable object is passed to iter() function.
  2. iterator is used to iterate over an iterable object using next() function.
  3. next() function always returns the next elements from the iterator.
  4. if there is no next element in the iterator then next() function raises Stopiteration exception.

Iterators can be iterable because both iterator and iterable can be iterated using for loop but iterable objects can not be iterator because next() method is not supported by iterable objects.

Popular Posts

Spread the knowledge
 
  

Leave a Reply

Your email address will not be published. Required fields are marked *