While writing an article about Generators, I realized that though iteration, iterable and iterator are so commonly used in programming; there is a certain degree of confusion around them. It’s crucial to understand the underlying concept for a better implementation. This is going to be a short and quick article to help us determine what is an iterable and what is an iterator.


Iteration

  • In layman’s language it is ‘repeating steps’.
  • Iteration in programming is a repetition of a block of code for a certain number of times.
  • This can be achieved by using loops.

Iterable

  • Iterable is an object which can be looped over or iterated over.
  • e.g. List, Tuple, Set, Dictionary, File.
  • In simpler words, iterable is a container which has data or values and we perform iteration over it to get elements one by one. (Can traverse through these values one by one)
  • Iterable has an in-built dunder method iter. A simpler way to determine whether an object is iterable is to check if it supports iter. How? Using dir( ), it returns the list of attributes and methods supported by an object.

Iterator

  • Iterator is an iterable object with a state so it remembers where it is during iteration.
  • e.g. Generator
  • Iterator performs the iteration to access the elements of the iterable one by one. As it maintains the internal state of elements, iterator knows how to get the next value.
  • Iterators can only move forward using _next _. It cannot go back or cannot be reset.
  • Iterator supports in-built dunder methods _iter _and next.

#iteration #python #data-science #programming #iterators

What are Iterables and Iterators in Python
1.20 GEEK