You are currently viewing Python Loops Cheat Sheet : Iterations in Python

Python Loops Cheat Sheet : Iterations in Python

1. For Loop

The for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

# Syntax
for variable in sequence:
    # Code to execute

# Example
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
    print(fruit)

2. While Loop

The while loop is used to repeatedly execute a block of code as long as the specified condition is true.

# Syntax
while condition:
    # Code to execute

# Example
count = 0
while count < 5:
    print(count)
    count += 1

3. Nested Loops

Python allows you to nest loops within each other, providing a way to perform more complex iterations.

# Example
for i in range(3):
    for j in range(3):
        print(i, j)

4. Loop Control Statements

Python provides control statements that allow you to alter the flow of a loop. The break statement terminates the loop, while the continue statement skips the rest of the code in the current iteration.

# Example (break)
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
    if fruit == 'banana':
        break
    print(fruit)

# Example (continue)
numbers = [1, 2, 3, 4, 5]
for num in numbers:
    if num % 2 == 0:
        continue
    print(num)

5. Range Function

The range() function generates a sequence of numbers, commonly used with loops to iterate a specific number of times.

# Syntax
range(start, stop, step)

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

6. Enumerate Function

The enumerate() function is used to iterate over both the values and their indices.

# Example
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
    print(index, fruit)

7. List Comprehensions

List comprehensions provide a concise way to create lists. They can also be used to create loops in a single line.

# Example
squares = [x**2 for x in range(5)]
print(squares)

8. Zip Function

The zip() function is used to combine two or more iterables.

# Example
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 22]
for name, age in zip(names, ages):
    print(name, age)

9. Else Clause with Loops

In Python, loops can have an else clause which is executed when the loop condition becomes false.

# Example (for loop with else)
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
    print(fruit)
else:
    print("No more fruits left.")

# Example (while loop with else)
count = 0
while count < 5:
    print(count)
    count += 1
else:
    print("Loop completed.")

10. Pass Statement

The pass statement is a no-operation statement. It’s used when a statement is syntactically required but you want to do nothing.

# Example
for i in range(3):
    pass  # Placeholder for future code

11. Unpacking in Loops

You can unpack values directly in a loop to simplify code.

# Example
coordinates = [(1, 2), (3, 4), (5, 6)]
for x, y in coordinates:
    print(f"X: {x}, Y: {y}")

12. Reversed Function

The reversed() function is used to reverse the order of an iterable.

# Example
numbers = [1, 2, 3, 4, 5]
for num in reversed(numbers):
    print(num)

13. Looping Through Dictionaries

Dictionaries can be iterated through their keys, values, or key-value pairs.

# Example (keys)
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key in my_dict:
    print(key)

# Example (values)
for value in my_dict.values():
    print(value)

# Example (key-value pairs)
for key, value in my_dict.items():
    print(key, value)

14. Using Enumerate with a Start Value

You can specify the start value for the enumerate() function.

# Example
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits, start=1):
    print(index, fruit)

15. Looping with Break and Else

Combining break and else can be useful for scenarios where you want to break out of a loop early and still perform some actions.

# Example
for i in range(5):
    if i == 3:
        print("Breaking loop early.")
        break
else:
    print("Loop completed.")

Leave a Reply