Python

Python for() Loop: Usage and Examples

arage.com@gmail.com

A for loop is a control structure that allows you to repeatedly execute a block of code. It is used to iterate over a specific sequence or a defined range of values.

Basic Syntax of Python For Loop

The basic syntax of a for loop in Python is as follows:

1for item in sequence:
2    # Code to be executed

In this structure, the for loop iterates over each item in the sequence, and in each iteration, the code block is executed. The “item” represents the current element in the sequence, and you can perform operations on it within the loop.

Types of Sequences for For Loop

Python’s for loop can iterate over various types of sequences. Here are some examples:

  • list
  • tuple
  • string
  • dictionary
  • set
  • The range() function, and more

Example using list

1fruits = ['apple', 'banana', 'orange']
2
3for fruit in fruits:
4    print(fruit)

Output:

apple
banana
orange

Example using tuple

1fruits = ('apple', 'banana', 'orange')
2
3for fruit in fruits:
4    print(fruit)

Output:

apple
banana
orange

Example using string

1message = "Hello, world!"
2
3for char in message:
4    print(char)

Output:

H
e
l
l
o
,
 
w
o
r
l
d
!

Example using dictionary

1student_scores = {
2    'Alice': 85,
3    'Bob': 92,
4    'Charlie': 78,
5    'David': 90
6}
7
8for name, score in student_scores.items():
9    print(name, "scored", score)

Output:

Alice scored 85
Bob scored 92
Charlie scored 78
David scored 90

Example using set

1fruits = {'apple', 'banana', 'orange'}
2
3for fruit in fruits:
4    print(fruit)

Output:

apple
banana
orange

Example using range

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

Output:

1
2
3
4
5

Advanced Features of For Loop

Using the else Block

1for item in sequence:
2    # Code to be executed
3else:
4    # Code to be executed after the loop completes

Python’s for loop allows an optional else block. The else block is executed after the completion of the loop, but only if the loop runs to completion without encountering a break statement.

Step Size and Using the range() Function

1for i in range(start, stop, step):
2    # Code to be executed

You can specify a step size when using the range() function to generate a sequence of numbers within a given range. This can be useful when incrementing or decrementing values in a loop.

Python range(): Usage and Examples
Python range(): Usage and Examples

Advanced Techniques for For Loop

Accessing Indexes

To access both the elements and their corresponding indexes in a for loop, you can use the enumerate() function. It returns a tuple containing the index and the item itself.

1for index, item in enumerate(sequence):
2    # Code to be executed

Creating Your Own Iterable Objects

Python allows you to create custom iterable objects by implementing the __iter__() and __next__() methods in a class. This enables you to iterate over your own objects using a for loop.

1class MyIterable:
2    def __iter__(self):
3        # Code to return an iterator object
4        ...
5
6    def __next__(self):
7        # Code to return the next element
8        ...

Best Practices and Considerations for For Loop

Guidelines for Code Readability and Simplicity

  • Use proper indentation to visually separate the code block within the loop.
  • Provide appropriate comments and use meaningful variable names to explain the code.
  • Utilize Python-specific features like list comprehensions and generator expressions to simplify the code.

Differences Between Python’s For Loop and Other Languages

Python’s for loop differs from the for loops in other programming languages. Python’s for loop iterates over iterable objects, eliminating the need for explicit indexes or counter variables. This leads to simpler and more readable code.

記事URLをコピーしました