For Loop in Python

 


The for loop in Python is used to iterate over a sequence (such as a list, tuple, string, or range) and execute a block of code for each item in that sequence. It’s one of the most commonly used loops in Python because of its simplicity and flexibility.

Basic Syntax of for loop:

  • for variable in sequence:

  •     # Code block to execute


  • variable: This is a temporary variable that takes the value of each item in the sequence, one at a time.

  • sequence: This is the collection or iterable (like a list, tuple, string, or range) that the loop will iterate over.

  • Code block: The indented block of code that will be executed for each item in the sequence.

Example 1: Simple for Loop Over a List

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

  • for fruit in fruits:

  •     print(fruit)


Output:

  • apple

  • banana

  • cherry


In this example:

  • The loop iterates over each item in the fruits list, and for each iteration, it prints the current fruit.

Example 2: for Loop with a Range

The range() function is commonly used with the for loop to generate a sequence of numbers.

  • for i in range(5):

  •     print(i)


Output:

  • 0

  • 1

  • 2

  • 3

  • 4


Here:

  • The range(5) generates numbers from 0 to 4, and the loop prints each number.

Example 3: for Loop with Strings

You can use a for loop to iterate over each character in a string.

  • message = "Python"

  • for char in message:

  •     print(char)


Output:

  • P

  • y

  • t

  • h

  • o

  • n


In this case:

  • The loop iterates over each character in the string "Python" and prints each character.

Example 4: for Loop with a Dictionary

You can also iterate over a dictionary using a for loop. By default, it will iterate over the keys, but you can access the keys and values.

  • person = {"name": "Alice", "age": 25, "city": "New York"}


  • # Iterating over keys

  • for key in person:

  •     print(key)


  • # Iterating over keys and values

  • for key, value in person.items():

  •     print(key, ":", value)


Output:

  • name

  • age

  • city


  • name : Alice

  • age : 25

  • city : New York


  • The first loop prints only the keys of the dictionary.

  • The second loop prints both the keys and their associated values.

Example 5: for Loop with else Block

You can use an else block with a for loop. The code inside the else block will be executed after the loop completes normally (without a break).

  • for i in range(3):

  •     print(i)

  • else:

  •     print("Loop finished!")


Output:

  • 0

  • 1

  • 2

  • Loop finished!


  • After the loop finishes, the else block is executed, printing "Loop finished!".

Example 6: Nested for Loop

You can use a for loop inside another for loop. This is called a nested for loop.

  • for i in range(1, 4):

  •     for j in range(1, 4):

  •         print(f"i={i}, j={j}")


Output:

  • i=1, j=1

  • i=1, j=2

  • i=1, j=3

  • i=2, j=1

  • i=2, j=2

  • i=2, j=3

  • i=3, j=1

  • i=3, j=2

  • i=3, j=3


  • In this example, the outer loop runs 3 times (with i values from 1 to 3), and for each iteration of the outer loop, the inner loop also runs 3 times.

Key Points about for Loop:

  • The for loop is iterative, meaning it iterates over a sequence, executing the code for each item.

  • You can use range() to generate a sequence of numbers, and iterate over that range.

  • You can iterate over different types of sequences, like lists, tuples, dictionaries, strings, and sets.

  • The else block runs when the loop finishes normally, but not if it’s interrupted by a break.

Good Practices:

  • Use the for loop when you know in advance the sequence you want to iterate over (such as a list or a range of numbers).

  • Use for loops for iterating over collections (e.g., lists, strings, dictionaries).

  • Be mindful when using nested loops; excessive nesting can make the code harder to read and less efficient.

Let me know if you'd like more examples or clarifications! 😊


Post a Comment

0 Comments