πŸ“€Iterables

What is an Iterable?

When a programming language goes through a collection of elements (say, a list) in any fashion, it is said to be "iterating over" that collection. Collections of elements that can be iterated over by Python are known as iterables.

We'll be discussing three iterables in this section: lists, tuples, and ranges.

Lists

This is the most common form of iterable, and one you've almost certainly already used. It looks something like this:

>>> lst = [1, 2, 3, 4]

You can index into it to retrieve an element, starting at zero.

>>> lst[0]
1
>>> lst[1]
2

You can also edit this list in a similar fashion.

>>> lst[0] = 5
>>> lst
[5, 2, 3, 4]

Tuples

Tuples are extremely similar to lists, with one key difference β€” while lists can be edited (are mutable), tuples are immutable. You cannot change them once you've created them.

>>> t = (1, 2, 3, 4)
>>> t[0]
1
>>> t[0] = 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

Note the error: It essentially states that tuples cannot be assigned elements once they are created.

Range

You might have used the range(start, stop, step) function before in for loops, something like the following:

for i in range(1, 10, 2):
    print(i)
# prints 1 3 5 7 9

We have not, however, stopped to consider what the call to the range function returns. Let's instead investigate this:

>>> r = range(10)
>>> r
range(0, 10)
>>> type(r)
class 'range'

Note how the range function doesn't return a list or a tuple but something else unique. This something else unique is an immutable sequence. The following example gives us insight on the immutability of range:

>>> r[3] = 4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'range' object does not support item assignment

Notice how the error is the same as the one for tuples! We can also perform the same operations as that of lists on ranges β€”Β indexing, slicing and so on.

Last updated