Turn Messy Text into Structured Insights With AI. Join Greg Live: Dec 4th, 2024
Leverage
Glossary

Iterable

Iterate through collections in Python. Define iterables, iterate, iterator, and iteration. Use enumerate for index retrieval

In Python, you often want to iterate (or process one by one) a collection of items. This could be rows in a dataset, items in a list, or keys in a dictionary. These are examples of a python iterable.

Iterables are collections of things that are able to be processed one-by-one, usually through a for loop.

“Under the hood”, an iterable is any Python object with an __iter__() method or with a __getitem__() method. If you’re just starting out, don’t worry about this detail and go have fun.

# This list is an iterable
my_list = [1,2,3,4,6]
for i in my_list:
    print (i)
>>> 1
>>> 2
>>> 3
>>> 4
>>> 6

Python Iterable: More definitions

Let’s cover the basic vocabulary words. They look the same, but refer to slightly different concepts

  • Iterable – (noun, object) – Anything that you can ‘iterate’ through. Or step through it’s items one by one. Ex: List, dictionary, dataframe
  • Iterate – (verb) – The act of going through an iterable (above) one by one
  • Iterator – (noun, object) – The thing doing the iterating of the iterable. Ex: For loop or map function.
  • Iteration – (noun, process) – The process of going through an iterable. Ex: “During the iteration of the list, a problem happened”

Bring it all together: “While you iterate through your iteratable with your iterator, you are in the process of iteration.”

Enumerate

One concept widely used is the enumerate command. While you are iterating through your iterable, you’ll get the values of the iterable returned to you. However, it’s useful to have the index of that value returned to you as well.

This is where enumerate comes in. Surround your iterable with enumerate and you’ll have two values returned.

# This list is an iterable
my_list = ["Bob","Sally"]
for i, value in enumerate(my_list):
    print (i)
    print (value)
    
>>> "Bob"
>>> 0
>>>
>>> "Sally"
>>> 1
>>>

Let’s look at a code example:

Link to code

On this page