π€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:
You can index into it to retrieve an element, starting at zero.
You can also edit this list in a similar fashion.
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.
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:
We have not, however, stopped to consider what the call to the range function returns. Let's instead investigate this:
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:
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