Back to: Python Programming
Iterables = An object/collection that can return its elements one at a time, allowing it to be iterated over in a loop.
Let’s create a list of numbers (recall a list is a 1D array).
Lists are considered iterable, we can use them in a for loop. In the context of a for loop, we’re going to be given each element one at a time. For each element that we’re working with, we can give a temporary nickname, like item or number (this name should be descriptive of what we’re iterating over for code readability):
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)
You could iterate backwards by enclosing our iterable into the reversed function, we’ll also send the output to a single line by replacing the new line character (the default) with end=” “ or end=”-“ or end=” – “:
numbers = [1, 2, 3, 4, 5]
for number in reversed(numbers):
print(number, end=" ")
Tuples are also iterable, convert your list to a tuple by enclosing our numbers with ():
numbers = (1, 2, 3, 4, 5)
for number in numbers:
print(number, end=" ")
Sets are iterable – create a set of fruits:
fruits = {"apple", "orange", "banana", "coconut"}
for fruit in fruits:
print(fruit)
Sets are NOT reversible – when enclosed in a reversed function, we get a type error.
Strings are iterable:
name = "Bob Down"
for character in name:
print(character)
Dictionaries are iterable. Iterating over a Dictionary will return all of the Keys but not the Values:
my_dictionary = {'A': 1, 'B': 2, 'C': 3}
for key in my_dictionary:
print(key)
If you need the values we use the built-in values method:
my_dictionary = {'A': 1, 'B': 2, 'C': 3}
for value in my_dictionary.values():
print(value)
If you need both the keys and the values, we use the items method:
my_dictionary = {'A': 1, 'B': 2, 'C': 3}
for key, value in my_dictionary.items():
print(key, value)
Tidy up the output with an f-string:
my_dictionary = {'A': 1, 'B': 2, 'C': 3}
for key, value in my_dictionary.items():
print(f"{key} = {value}")