Iteration
-
Definition: a repetition of a process
-
used for an indefinite number of iterations
- Loops are control structures for codeblock iteration
-
Repeatedly execute codeblack when the expression is True
- Boolean expression determines the execution of a codeblock
Iterating through an Iterable
- Iterable
- An object that can be iterated or repeatedly applied
- All sequences and containers are iterable
- Has items that can be accessed.
Iterable For Loops in list - Example
# Define a list of numbers
numbers = [1, 2, 3, 4, 5]
# Iterate over each element in the list using a for loop
for num in numbers:
print(num)
'''
for item in my_list:
print(item)
'''
Example using a for loop to repeat an action
for i in range(5):
print("Hello, world!")
Example using break to exit a loop early
for number in range(10):
if number == 5:
break
print(number)
Iterable While Loops in list - Example
mylist = ['a','b','c']
# iterable mylist
i=0
# called index number
while i < len(mylist):
ch = mylist[i]
print(ch)
i = i+1
Example using while loop to repeat until condition is false
count = 0
while count < 5:
print(count)
count += 1
Iteration with Dictionaries
- can be done over
keys
orkey-value
pairs usingfor
loops anditems()
method - Dictionary comprehension is used to create a new dictionary based on existing key-value pairs.
# Iterating over a dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}
# Iterating over keys
print("\nIterating over keys in a dictionary:")
for key in my_dict:
print(key)
# Iterating over key-value pairs
print("\nIterating over key-value pairs in a dictionary:")
for key, value in my_dict.items():
print(f"Key: {key}, Value: {value}")
# Using dictionary comprehension
print("\nCreating a new dictionary with comprehension:")
double_dict = {key: value * 2 for key, value in my_dict.items()}
print(double_dict)
Iteration with Tuples
- Tuples are iterated over similarly to lists, using a for loop. Tuple unpacking (enumerate function) can provide both index and value during iteration. Unlike lists and dictionaries, tuples do not support direct comprehension, but you can use a generator expression to achieve a similar effect.
# Iterating over a tuple
my_tuple = (1, 2, 3, 4, 5)
# Using a for loop
print("\nIterating over a tuple:")
for item in my_tuple:
print(item)
# Using tuple unpacking
print("\nIterating over a tuple with unpacking:")
for i, item in enumerate(my_tuple):
print(f"Index: {i}, Value: {item}")
# Using tuple comprehension
# (not directly available, but you can use generator expression)
print("\nCreating a new tuple with generator expression:")
squared_tuple = tuple(x**2 for x in my_tuple)
print(squared_tuple)