0% completed
The for
loop in Python is a versatile control structure that allows you to iterate over a sequence of elements, such as lists, tuples, strings, or any other iterable object. This type of loop is particularly useful for tasks that require the execution of a block of code for each element in a sequence.
In this lesson, we will explore the syntax, basic usage, and some advanced concepts associated with the for
loop in Python.
Syntax of the for Loop
The basic syntax of a for
loop in Python is as follows:
Explanation:
iterable
: This is the collection of elements that the loop will iterate over. It can be a list, a tuple, a dictionary, a set, or any object that supports iteration.variable
: For each iteration of the loop, thevariable
takes on the value of the next element in theiterable
.
Basic Example
Let’s look at a simple example to understand the basic functionality of the for
loop.
Explanation:
fruits = ['apple', 'banana', 'cherry']
: Defines a list of fruits.for fruit in fruits:
: Starts a loop over thefruits
list. With each iteration, the variablefruit
will take the value of one item from the list.print(fruit)
: Executes for each iteration of the loop, printing the current value offruit
.
This example demonstrates how to use a for
loop to iterate over a list and perform an action with each element, which in this case is printing the element. This approach is clear and concise, avoiding the need for indexing and the associated risks of off-by-one errors or boundary issues.
Looping Through Dictionaries
Dictionaries in Python are key-value pairs. You can iterate over them in several ways, depending on whether you need access to keys, values, or both.
Example
Explanation:
info = {'name': 'John', 'age': 30, 'city': 'New York'}
: Initializes a dictionary with three key-value pairs.for key in info:
: Iterates over each key in the dictionary by default. If you need to iterate over values or key-value pairs, you could useinfo.values()
orinfo.items()
, respectively.print(key, "->", info[key])
: Prints each key and its corresponding value. To directly access both key and value in the loop, usefor key, value in info.items():
.
Nested Loops
A nested loop is a loop inside a loop. The "inner loop" will be executed one time for each iteration of the "outer loop".
Example
Explanation:
matrix = [[1, 2, 3], [4, 5, 6]]
: Sets up a list containing two lists, each with three integers.for row in matrix:
: The outer loop iterates over each sublist inmatrix
.for num in row:
: The inner loop iterates over each element in the current sublist referred to byrow
.print(num, end=' ')
: Prints each number followed by a space instead of the default newline.print()
: After the inner loop completes for a sublist, it prints a newline to separate the rows visually.
Using the range() Function with Loops
The range()
function in Python is frequently used with for
loops to generate sequences of numbers. This function is extremely versatile and beneficial when you need to execute a loop a specific number of times. The range()
function can be used in several ways depending on the parameters provided:
- Single parameter: Generates a sequence from 0 up to, but not including, the specified number.
- Two parameters: Generates a sequence from the first parameter to the second parameter, not including the second parameter.
- Three parameters: The third parameter specifies the step, or increment, between each number in the sequence.
Example
Explanation:
for i in range(10):
: Iterates over numbers 0 through 9. It usesrange(10)
which starts at 0 (default) and ends at 9 (one less than 10).for i in range(1, 11):
: Iterates from 1 to 10. It specifies the starting point of 1 and goes up to 10.for i in range(1, 11, 2):
: Iterates starting from 1 up to 10, incrementing by 2 each time, thus printing only odd numbers between 1 and 10.
The for loop in Python is an indispensable tool for iterating over sequences and performing repeated operations efficiently. By mastering this loop, along with utilities like the range() function, you can handle most common looping requirements with ease and clarity. Whether you're processing items in a list, executing tasks a specific number of times, or combining it with conditions and other control structures, the for loop enhances readability and reduces the chance for errors in your code.
.....
.....
.....
Table of Contents
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible