Python From Beginner to Advanced

0% completed

Previous
Next
Python - for loop

Loops are fundamental programming structures that allow repetitive execution of a block of code while certain conditions are met. They are incredibly useful for tasks that require the same action or a similar set of actions to be performed multiple times, which is a common scenario in programming. Python provides several loop constructs that enable these repetitive actions to be handled in an efficient, readable, and concise manner.

Python - for Loop

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:

Image
Python3
Python3
. . . .

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, the variable takes on the value of the next element in the iterable.

Basic Example

Let’s look at a simple example to understand the basic functionality of the for loop.

Python3
Python3

. . . .

Explanation:

  • fruits = ['apple', 'banana', 'cherry']: Defines a list of fruits.
  • for fruit in fruits:: Starts a loop over the fruits list. With each iteration, the variable fruit will take the value of one item from the list.
  • print(fruit): Executes for each iteration of the loop, printing the current value of fruit.

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.

Example: 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.

Python3
Python3

. . . .

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 use info.values() or info.items(), respectively.
  • print(key, "->", info[key]): Prints each key and its corresponding value. To directly access both key and value in the loop, use for 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

Python3
Python3

. . . .

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 in matrix.
  • for num in row:: The inner loop iterates over each element in the current sublist referred to by row.
  • 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:

  1. Single parameter: Generates a sequence from 0 up to, but not including, the specified number.
  2. Two parameters: Generates a sequence from the first parameter to the second parameter, not including the second parameter.
  3. Three parameters: The third parameter specifies the step, or increment, between each number in the sequence.

Example

Python3
Python3

. . . .

Explanation:

  • for i in range(10):: Iterates over numbers 0 through 9. It uses range(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.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next