Python Morsels: What is an iterable?

Related Articles:

Transcript

An iterable is anything you're able to iterate over (an iter-able).

Manual iteration using for loop

If you can write a for loop to loop over something in Python, that something is an iterable.

Here's a list, a tuple, a string, and a set:

>>> fruits = ['apple', 'lemon', 'pear', 'watermelon']>>> coordinates = (1, 8, 2)>>> greeting = "Hi y'all!">>> colors = {'red', 'blue', 'yellow'}

All of these are iterables.

The usual way to iterate over something is to write a for loop:

>>> for fruit in fruits:...     print(fruit)...applelemonpearwatermelon

As we loop over the fruits list above, we're assigning the variable fruit to each each item in the list and then doing something with it (printing in this case) inside the body of our loop.

The above for loop works, which means fruits is an iterable.

All iteration utilities do the same kind of looping

A for loop isn't the only way to iterate over an iterable.

For example, the list constructor does iteration as well.When we pass an iterable to the list constructor, it'll loop over it and make a new list out of its items:

>>> list(coordinates)[1, 8, 2]

Here we've looped over a tuple (coordinates) and created a list out of it.

Strings are iterables too.As you loop over a string, you'll get each of the characters in that string:

>>> list(greeting)['H', 'i', ' ', 'y', "'", 'a', 'l', 'l', '!']

Just like above, we're relying on the list constructer to do the looping (and list creating) for us.

Sets are also iterables, so we can loop over the colors set, either with a for loop or with a function (like the list constructor) that'll loop for us:

>>> list(colors)['yellow', 'blue', 'red']

Summary

We've seen that lists, tuples, sets, and strings are iterables.

Dictionaries, generators and files are also iterables.There are lots of other iterables in the Python, both built-in and included in third-party libraries.

Anything that you can write a for loop to loop over, it is an iterable.

Iterables might not have a length and you might not be able to index them.They might not even be finite (there are infinitely long iterables in Python)!

But if you can write a for loop to loop over something, it is an iterable.

POst ID: 2648111212