Iterables

Published

2023-07-31

Iterables

As we have seen, iterables are Python’s way of controlling a for loop.

You can think of an iterable as a sequence or composite object (composed of many parts) which can return one element at a time, until the sequence is exhausted. We usually refer to the elements of an iterable as members of the iterable.

It’s much like dealing playing cards from a deck, and doing something (performing a task or calculation) once for each card that’s dealt.

A deck of playing cards is an iterable. It has 52 members (the individual cards). The cards have some order (they may be shuffled or not, but the cards in a deck are ordered nonetheless). We can deal cards one at a time. This is iterating through the deck. Once we’ve dealt the 52nd card, the deck is exhausted, and iteration stops.

Now, there are two ways we could use the cards.

First, we can use the information that’s encoded in each card. For example, we could say the name of the card, or we could add up the pips on each card, and so on.

Alternatively, if we wanted to do something 52 times (like push-ups) we could do one push-up for every card that was dealt. In this case, the information encoded in each card and the order of the individual cards would be irrelevant. Nevertheless, if we did one push-up for every card that was dealt, we’d know when we reached the end of the deck that we’d done 52 push-ups.

So it is in Python. When iterating some iterable, we can use the data or value of each member (say calculating the sum of numbers in a list), or we can just use iteration as a way of keeping count. Both are OK in Python.

Using the data provided by an iterable

Here are two examples of using the data of members of an iterable.

First, assume we have a list of integers and we want to know how many of those numbers are even and how many are odd. Say we have such a list in a variable named lst.

evens = 0

for n in lst:
    if n % 2 == 0:  # it's even
        evens += 1
        
print(f"There are {evens} even numbers in this list, "
      f"and there are {len(lst) - evens} odd numbers.")

As another example, say we have a list of all known periodic comets, and we want to produce a list of those comets with an orbital period of less than 100 years. We would iterate through the list of comets, check to see each comet’s orbital period, and if that value were less than 100 years, we’d append that comet to another list. In the following example, the list COMETS contains tuples in which the first element of the tuple is the name of the comet, and the second element is its orbital period in years.1

"""
Produce a list of Halley's type periodic comets 
with orbital period less than 100 years.
"""
COMETS = [('Mellish', 145), ('Sheppard–Trujillo', 66), 
          ('Levy', 51), ('Halley', 75), ('Borisov', 152), 
          ('Tsuchinshan', 101), ('Holvorcem', 38)]
          # This list is abridged. You get the idea.

short_period_comets = []

for comet in COMETS:
    if comet[1] < 100:
        short_period_comets.append(comet)
        # Yes, there's a better way to do this, 
        # but this suffices for illustration.

Here we’re using the data encoded in each member of the iterable, COMETS.

Using an iterable solely to keep count

for _ in range(1_000_000):
    print("I will not waste chalk")

Here we’re not using the data encoded in the members of the iterable. Instead, we’re just using it to keep count. Accordingly, we’ve given the variable which holds the individual members returned by the iterable the name _. _ is commonly used as a name for a variable that we aren’t going to use in any calculation. It’s the programmer’s way of saying, “Yeah, whatever, doesn’t matter what value it has and I don’t care.”

So these are two different ways to treat an iterable. In one case, we care about the value of each member of the iterable; in the other, we don’t. However, both approaches are used to govern a for loop.

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

This material is for free use under either the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 United States License (take your pick).

Footnotes

  1. The orbital period of a comet is the time it takes for the comet to make one orbit around the sun.↩︎