For Loops
For Loops
ipynb - Colab
Motivation
Welcome to your journey of learning about for loops and iteration in programming! Let's explore
the key reasons why learning about for loops and iteration is valuable:
Automatic Repetition: For loops help you do the same task again and again without writing
repetitive code. It's like having a robot that can do a task for each item in a group.
Data Processing and Transformation: For loops are great for working with large amounts
of data. They help you process and change the data systematically.
Code Reusability and Scalability: For loops make your code flexible and ready for the
future. They let you write code that can handle different amounts of data easily.
In programming, iteration allows you to perform tasks repeatedly until a certain condition is met.
Loops are the primary construct used for iteration in Python.
An iterable is an object that can be iterated over, meaning it can be used in a loop.
It provides a sequence of values that can be accessed one at a time. Common iterable objects in
Python include strings, lists, tuples, sets, and dictionaries.
This form of iteration is called definite iteration, where the number of iterations is known. Further,
this is an example of Don't Repeat Yourself (DRY) coding, since a single for loop performs
As opposed to the while loop, the for loop is limited by the number of items in
the iterable.
keyboard_arrow_down Syntax
The syntax of a for loop in Python is as follows:
The item represents the current item in the sequence. For readability, the best practice is
to use naming words, such as city in cities , item in items , where cities or items
are the name of the iterable.
item refers to each element in the iterable in a given iteration; thus, we can employ item in
the do_something block
sequence is the data structure over which the operation is performed. The sequence can
be a string, list, tuple, or any other iterable object.
colon indicates control flow and signals an indentation, completing the set phrase
Strings
message = "Hello"
for char in message:
print(char)
H
e
l
l
o
keyboard_arrow_down Lists
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
apple
banana
cherry
keyboard_arrow_down Tuples
point = (3, 7)
for coordinate in point:
print(coordinate)
3
7
keyboard_arrow_down Sets
colors = {"red", "green", "blue"}
for color in colors:
print(color)
blue
red
green
keyboard_arrow_down Dictionaries
student = {"name": "Alice", "age": 20, "grade": "A"}
for key in student:
print(key, student[key])
name Alice
age 20
grade A
In this example, the keys represent different attributes of the student, such as "name" , "age" ,
and "grade" , while the corresponding values hold the actual data.
The for loop iterates over the keys of the student dictionary. In each iteration, the loop variable
key takes on the value of each key in the dictionary.
Inside the loop, we access the value associated with each key using the square bracket notation
( student[key] ). This allows us to retrieve the corresponding value from the student dictionary
based on the current key.
When iterating over dictionaries, you have a few other options to access both the keys and
values. Let's consider the following dictionary as an example:
You can iterate directly over the keys of a dictionary using the d.keys() method. The d.keys()
method returns a view object that represents the keys of the dictionary. Here's an example:
name
age
grade
In this example, we iterate over the keys of the student dictionary using the student.keys()
method. In each iteration, the loop variable key holds the current key from the dictionary.
You can perform operations on the key or use it to access the corresponding value
in the dictionary.
The d.items() method returns a view object that represents the key-value pairs of a dictionary
as tuples. You can use tuple unpacking to iterate over both the keys and values simultaneously.
Here's an example:
name Alice
age 20
grade A
In this example, we iterate over the key-value pairs of the student dictionary using the
student.items() method. In each iteration, the loop variables key and value hold the current key
and its associated value from the dictionary, respectively. You can perform operations on both
the key and value within the loop body.
Using d.items() you can perform operations on the keys and values of a
dictionaries within the loop body.
For example:
In this example, within the loop body, we perform operations based on different specific keys. In
this case, we check if the key is equal to "name" , "age" , or "grade" and print the corresponding
information about the student. If the key does not match any of these conditions, we print
"Unknown attribute" .
The range() function returns an iterable sequence of numbers that can be used in a for loop.
Here's an example:
1
2
3
4
In this example, the range(1, 5) generates a sequence of numbers from 1 to 4 (excluding 5).
The for loop iterates over this sequence, and in each iteration, the loop variable i takes on the
current value from the sequence.
1
3
5
7
9
In this example, the range(1, 10, 2) generates a sequence of odd numbers from 1 to 9, in
steps of 2.
[1, 2, 3, 4, 5]
In this example, the range(1, 6) generates a sequence of numbers from 1 to 5 (exclusive). The
list() function is used to convert the sequence into a list, which is then assigned to the
variable numbers.
If we print the type of range(1,6) and list(range(1,6)) we will see more clearly the difference:
print(type(range(1,6)))
print(type(list(range(1,6))))
<class 'range'>
<class 'list'>
The range(len(iterable)) is a useful construct that combines the range() function with the
len() function to iterate over the indices of an iterable object. Here's how it works:
for i in range(len(fruits)):
print(i, fruits[i])
0 apple
1 banana
2 cherry
In this example, len(fruits) returns the length of the fruits list, which is 3 . The
range(len(fruits)) generates a sequence of numbers from 0 to 2 (exclusive). The loop iterates
over this sequence, and in each iteration, the loop variable i takes on the current value from the
sequence. By using fruits[i] , we can access the element at index i in the fruits list.
This construct is useful when you need both the index and the corresponding
value of each element in an iterable object. It allows you to perform operations or
access specific elements based on their indices within the loop body.
break
The break statement is used to exit the loop prematurely. It terminates the loop and transfers
control to the next statement outside the loop. Here's an example:
1
2
3
In this example, the loop is interrupted when i equals 4 , and the loop is terminated, skipping
the remaining iterations.
keyboard_arrow_down continue
The continue statement is used to skip the rest of the current iteration and move to the next
iteration. It jumps to the next iteration without executing the remaining statements in the loop
body. Here's an example:
1
2
4
5
In this example, the loop skips the iteration when i equals 3 , and the remaining statements
within the loop body are not executed. The loop then proceeds to the next iteration.
keyboard_arrow_down else
The else statement in a for loop is executed when the loop has exhausted all the items in the
iterable. It is not executed if the loop is terminated by a break statement. Here's an example:
1
2
https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/15. For Loops%2C… 8/13
4/25/24, 10:35 PM Notebook.ipynb - Colab
3
4
Loop completed successfully!
In this example, the loop completes all iterations, so the else block is executed, and the
corresponding message is printed.
In Python, the pass keyword is used as a placeholder when you need a statement syntactically,
but you don't want to add any code or perform any action. It is often used in combination with for
loops to create empty loops or to temporarily skip the implementation of certain parts. Here's
how the pass keyword can be used with for loops:
Empty Loop
An empty loop is a loop that doesn't contain any statements inside its body. It is used when you
want to create a loop structure but leave the implementation details empty. The pass keyword is
used as a placeholder in this case. Here's an example:
for i in range(5):
pass
In this example, the loop iterates five times, but since there is no code inside the loop body, the
pass keyword serves as a placeholder. It allows the loop to iterate without performing any
specific actions.
In this example, the pass keyword is used as a placeholder for the code that is yet to be
implemented. It allows you to keep the loop structure intact and continue with the rest of the
iterations. Later, you can come back and fill in the necessary code.
The pass keyword provides a way to maintain the syntactical correctness of your code when you
need an empty or incomplete loop structure. It can be particularly useful in the following
scenarios:
Placeholder for future code: When you want to create a loop structure but haven't yet
decided on the specific actions to be performed within the loop body, you can use pass as
a temporary placeholder until you're ready to add the code
Code organization: When working on a larger codebase, you may want to outline the
structure of your loops first and then fill in the details later. By using pass , you can create
empty loops and come back to them at a later time without causing any syntax errors.
Stubbing out code: When collaborating with others or working on a project with multiple
developers, you can use pass to indicate that a particular section of the code is still in
progress or requires someone else's implementation.=
In Python, the zip and enumerate functions are commonly used in conjunction with for loops
to iterate over multiple iterables or to retrieve both the index and the value of each item in an
iterable. Let's explore these functions in more detail.
zip function
The zip function allows you to combine multiple iterables into a single iterable of tuples. Each
tuple contains the corresponding elements from all the iterables. Here's how it works:
iterable1 = [1, 2, 3]
iterable2 = ['a', 'b', 'c']
1 a
2 b
3 c
In this example, the zip function pairs the elements from iterable1 and iterable2 together.
The for loop then iterates over the resulting iterable of tuples, and each tuple is unpacked into
item1 and item2 . This allows you to access and work with corresponding elements from
different iterables simultaneously.
It's worth noting that zip stops iterating as soon as one of the input iterables is
exhausted. If the input iterables have different lengths, the resulting iterable will
https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/15. For Loops%2… 10/13
4/25/24, 10:35 PM Notebook.ipynb - Colab
The enumerate function provides an elegant way to iterate over an iterable while also retrieving
the index of each item. Here's an example:
0 a
1 b
2 c
In this example, the enumerate function adds an index to each item in the iterable. The for loop
iterates over the resulting iterable of tuples, and each tuple is unpacked into index and item. This
allows you to access both the index and the value of each item in the iterable within the loop.
By default, enumerate starts the index from 0 , but you can specify a different starting value by
passing it as the second argument to the function, like enumerate(iterable, start=1) .
Nested for loops are particularly useful when working with multidimensional data structures or
when you need to perform operations on combinations of elements from different iterables.
In this example, there are two lists: teams and players . The outer loop iterates over each team
in the teams list, and for each team, the inner loop iterates over each player in the players list.
The print statement inside the nested loops outputs the combination of players and teams.
Nested for loops can also be used with other types of iterables, such as strings or ranges.
When working with nested for loops, it's crucial to pay attention to the indentation
to ensure proper nesting. Each level of indentation indicates the scope of the loop
and its associated block of code.
Infinite loops
Infinite loops occur when the loop condition or iteration logic is incorrect, causing the loop to
continue indefinitely. Check your loop condition and ensure that it eventually evaluates to False
to exit the loop. Additionally, ensure that your loop logic includes a way to progress towards the
exit condition.
Incorrect indentation
Python relies on proper indentation to determine the scope of code blocks. Make sure your loop
body and any nested blocks are indented correctly. Inconsistent or incorrect indentation can lead
to syntax errors or unexpected behaviors.
Key Takeaways
For loops are used to iterate over elements in an iterable object such as strings, lists,
tuples, or ranges
The range() function is commonly used to generate a sequence of numbers that can be
used in for loops
Nested for loops allow you to perform repetitive actions within repetitive actions, enabling
you to handle multidimensional data structures and perform complex operations
The zip() function combines multiple iterables into a single iterable, allowing you to
iterate over them in parallel
The enumerate() function provides an index value along with the elements of an iterable,
making it useful when you need to track the index during iteration
Control statements such as break , continue , and else can be used within for loops to