Python Tutorial

Python Flow Control

Python Functions

Python Data Types

Python Date and Time

Python Files

Python String

Python List

Python Dictionary

Python Variable

Python Input/Output

Python Exceptions

Python Advanced

Python For Loops

In this tutorial, you'll learn how to use for loops in Python to iterate over sequences like lists, tuples, strings, and dictionaries. For loops in Python are useful for repeating a block of code for each item in a sequence.

  • Looping over a list:
fruits = ['apple', 'banana', 'cherry']

for fruit in fruits:
    print(fruit)
  • Looping over a tuple:
colors = ('red', 'green', 'blue')

for color in colors:
    print(color)
  • Looping over a string:
text = "Python"

for char in text:
    print(char)
  • Looping over a range:

You can use the range() function to generate a sequence of numbers, which is useful for repeating a block of code a specific number of times.

for i in range(5):
    print(i)
  • Looping over a dictionary:

When looping over a dictionary, you can use the items() method to iterate over key-value pairs, the keys() method to iterate over keys, or the values() method to iterate over values.

person = {
    'name': 'Alice',
    'age': 30,
    'city': 'New York'
}

# Looping over key-value pairs
for key, value in person.items():
    print(f"{key}: {value}")

# Looping over keys
for key in person.keys():
    print(key)

# Looping over values
for value in person.values():
    print(value)
  • Using the enumerate function:

The enumerate() function can be used to loop over a sequence and get both the index and the item at that index.

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

for index, fruit in enumerate(fruits):
    print(f"Index {index}: {fruit}")
  • Nested for loops:

You can have for loops inside other for loops to iterate over nested sequences, like a list of lists.

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

for row in matrix:
    for element in row:
        print(element, end=' ')
    print()  # Print a newline character

For loops are a powerful and flexible way to iterate over sequences in Python, allowing you to perform tasks on each element in a collection.

  1. Iterate through a list with a for loop in Python:

    • Description: Use a for loop to iterate through elements in a list.
    • Code:
      my_list = [1, 2, 3, 4, 5]
      for item in my_list:
          print(item)
      
  2. Nested for loops in Python:

    • Description: Utilize nested for loops for iterating through multiple dimensions.
    • Code:
      nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
      for sublist in nested_list:
          for item in sublist:
              print(item)
      
  3. Python range() function in a for loop:

    • Description: Use the range() function to generate a sequence in a for loop.
    • Code:
      for i in range(5):
          print(i)
      
  4. Looping through a dictionary with a for loop in Python:

    • Description: Iterate through key-value pairs in a dictionary.
    • Code:
      my_dict = {'a': 1, 'b': 2, 'c': 3}
      for key, value in my_dict.items():
          print(f'{key}: {value}')
      
  5. Python enumerate() function in a for loop:

    • Description: Use enumerate() to get both the index and value in a for loop.
    • Code:
      my_list = ['a', 'b', 'c']
      for index, value in enumerate(my_list):
          print(f'Index: {index}, Value: {value}')
      
  6. Break and continue statements in Python for loop:

    • Description: Control the flow of a for loop using break and continue.
    • Code:
      for i in range(10):
          if i == 5:
              break  # Exit the loop when i is 5
          print(i)
      
  7. Looping through strings with a for loop in Python:

    • Description: Iterate through characters in a string using a for loop.
    • Code:
      my_string = 'Hello'
      for char in my_string:
          print(char)
      
  8. Python zip() function in a for loop:

    • Description: Use zip() to iterate over multiple iterables in parallel.
    • Code:
      list1 = [1, 2, 3]
      list2 = ['a', 'b', 'c']
      for item1, item2 in zip(list1, list2):
          print(item1, item2)
      
  9. Iterate over a file line by line using a for loop in Python:

    • Description: Read and process lines from a file using a for loop.
    • Code:
      with open('example.txt', 'r') as file:
          for line in file:
              print(line.strip())
      
  10. For loop with else statement in Python:

    • Description: Execute code in the else block if the for loop completes without break.
    • Code:
      for i in range(5):
          if i == 3:
              print('Found 3')
              break
      else:
          print('Loop completed without break')
      
  11. Looping through a set with a for loop in Python:

    • Description: Iterate through elements in a set.
    • Code:
      my_set = {1, 2, 3, 4, 5}
      for item in my_set:
          print(item)
      
  12. Python list comprehension and for loop:

    • Description: Use list comprehension as a concise form of a for loop.
    • Code:
      my_list = [x**2 for x in range(5)]
      print(my_list)
      
  13. Iterate over multiple lists in parallel with a for loop in Python:

    • Description: Use zip() to iterate over multiple lists simultaneously.
    • Code:
      list1 = [1, 2, 3]
      list2 = ['a', 'b', 'c']
      for item1, item2 in zip(list1, list2):
          print(item1, item2)
      
  14. Looping through a 2D list with a for loop in Python:

    • Description: Iterate through elements in a 2D list.
    • Code:
      nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
      for sublist in nested_list:
          for item in sublist:
              print(item)