0% found this document useful (0 votes)
7 views

For Loops

The document discusses for loops in Python including their syntax, how they can be used to iterate over different iterable objects like strings, lists, tuples, dictionaries, and the range() function. It provides examples of iterating over these objects and using the keys, values, and items of dictionaries.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

For Loops

The document discusses for loops in Python including their syntax, how they can be used to iterate over different iterable objects like strings, lists, tuples, dictionaries, and the range() function. It provides examples of iterating over these objects and using the keys, values, and items of dictionaries.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

4/25/24, 10:35 PM Notebook.

ipynb - Colab

keyboard_arrow_down For Loops, Iteration and Control Flow Tricks


In this notebook we will continue learning about different control flow structures, focusing on
for loops.

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.

Iteration and Iterables

Iteration refers to the process of repeatedly performing a specific action or


executing a block of code.

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.

keyboard_arrow_down For Loops


For loops perform an operation on each element in an iterable (each character in a string or each
item in a list) until no element is left in the iterable. It repeatedly executes a block of code for
each item in the sequence.

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

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/15. For Loops%2C… 1/13


4/25/24, 10:35 PM Notebook.ipynb - Colab

numerous operations in one pass.

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:

for item in sequence:


# do_something
# do_something_to_i

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

in is a keyword referencing the iterable

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

do_something is the code block to be executed on each element

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/15. For Loops%2C… 2/13


4/25/24, 10:35 PM Notebook.ipynb - Colab

keyboard_arrow_down Common Iterable Objects


In this section, let's look at how we would use for loops to iterate over different iterable objects.

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

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/15. For Loops%2C… 3/13


4/25/24, 10:35 PM Notebook.ipynb - Colab

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:

student = {"name": "Alice", "age": 20, "grade": "A"}

keyboard_arrow_down Iterating through d.keys() :

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:

for key in student.keys():


print(key)

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.

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/15. For Loops%2C… 4/13


4/25/24, 10:35 PM Notebook.ipynb - Colab

keyboard_arrow_down Using tuple unpacking with d.items()

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:

for key, value in student.items():


print(key, value)

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:

student = {"name": "Alice", "age": 20, "grade": "A"}

for key, value in student.items():


if key == "name":
print(f"The student's name is {value}")
elif key == "age":
print(f"The student's age is {value}")
elif key == "grade":
print(f"The student's grade is {value}")
else:
print("Unknown attribute")

The student's name is Alice


The student's age is 20
The student's grade is A

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" .

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/15. For Loops%2C… 5/13


4/25/24, 10:35 PM Notebook.ipynb - Colab

keyboard_arrow_down The range() function


The range() function is commonly used in for loops to generate a sequence of numbers. It
takes up to three arguments: start , stop , and step . Here's the general syntax:

range(start, stop, step)

start (optional): The starting value of the sequence (default is 0)


stop : The ending value of the sequence (exclusive)
step (optional): The step size between each number in the sequence (default is 1)

The range() function returns an iterable sequence of numbers that can be used in a for loop.
Here's an example:

for i in range(1, 5):


print(i)

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.

keyboard_arrow_down Using a step size


for i in range(1, 10, 2):
print(i)

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.

keyboard_arrow_down Creating a list using list()

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/15. For Loops%2C… 6/13


4/25/24, 10:35 PM Notebook.ipynb - Colab

numbers = list(range(1, 6))


print(numbers)

[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'>

keyboard_arrow_down The range(len(iterable)) function

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:

fruits = ["apple", "banana", "cherry"]

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.

keyboard_arrow_down Control Statements


Control statements such as break , continue , and else can be used within for loops to modify
the flow of execution.

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/15. For Loops%2C… 7/13


4/25/24, 10:35 PM Notebook.ipynb - Colab

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:

for i in range(1, 6):


if i == 4:
break
print(i)

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:

for i in range(1, 6):


if i == 3:
continue
print(i)

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:

for i in range(1, 5):


print(i)
else:
print("Loop completed successfully!")

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.

keyboard_arrow_down pass Keyword and for loops

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.

keyboard_arrow_down Temporary Skip


The pass keyword can also be used to temporarily skip the implementation of a particular part
within a loop. This is useful when you are in the process of writing or designing your code and
want to skip a certain section until later. Here's an example:

for item in iterable:


if condition:
pass
# Code to be implemented later
else:
# Code to be executed for other iterations

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.

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/15. For Loops%2C… 9/13


4/25/24, 10:35 PM Notebook.ipynb - Colab

Usage and Benefits

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.=

keyboard_arrow_down zip and enumerate

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']

for item1, item2 in zip(iterable1, iterable2):


print(item1, item2)

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

only contain tuples up to the length of the shortest input iterable.

keyboard_arrow_down enumerate function

The enumerate function provides an elegant way to iterate over an iterable while also retrieving
the index of each item. Here's an example:

iterable = ['a', 'b', 'c']

for index, item in enumerate(iterable):


print(index, item)

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) .

keyboard_arrow_down Nested for loops


In Python, it is possible to have one or more for loops nested inside another for loop. This
concept is known as nested for loops, and it allows you to iterate over multiple levels of iterables,
creating a hierarchical or nested structure.

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.

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/15. For Loops%2… 11/13


4/25/24, 10:35 PM Notebook.ipynb - Colab

Here's an example of a simple nested for loop:

teams = ["Team A", "Team B", "Team C"]


players = ["Player 1", "Player 2", "Player 3"]

for team in teams:


for player in players:
print(f"{player} belongs to {team}")

Player 1 belongs to Team A


Player 2 belongs to Team A
Player 3 belongs to Team A
Player 1 belongs to Team B
Player 2 belongs to Team B
Player 3 belongs to Team B
Player 1 belongs to Team C
Player 2 belongs to Team C
Player 3 belongs to Team C

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.

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/15. For Loops%2… 12/13


4/25/24, 10:35 PM Notebook.ipynb - Colab

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.

Common Errors and Troubleshooting

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.

Modifying the iterated object


Avoid modifying the iterated object (e.g., a list) within the loop. Modifying the length or content
of the iterated object during iteration can result in unpredictable outcomes and errors. If you
need to modify the iterated object, consider creating a copy or using a different approach.

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

https://colab.research.google.com/github/AI-Core/Content-Public/blob/main/Content/units/Essentials/7. Python programming/15. For Loops%2… 13/13

You might also like