For Loops in Python
? For Loops in Python
A for loop in Python is used to iterate over a sequence (like a list, tuple, string, or range) and execute a block of code for each item in the sequence.
Basic Syntax:
for item in sequence: # Execute this block of code for each item # Indented code block? 1. Looping through a List
You can loop through a list and perform operations on each item.
fruits = ["apple", "banana", "cherry"]for fruit in fruits: print(fruit)Output:
applebananacherry
? 2. Looping through a String
You can iterate over each character in a string.
word = "hello"for letter in word: print(letter)Output:
hello
? 3. Using range() for Loops
The range() function generates a sequence of numbers, which is often used in for loops to repeat actions a specific number of times.
for i in range(5): print(i)Output:
01234Explanation:
range(5)generates numbers from0to4. The loop iterates over each of these numbers.
You can also specify a start and stop value in range().
for i in range(2, 6): print(i)Output:
2345
You can also define a step size:
for i in range(0, 10, 2): print(i)Output:
02468
? 4. Nested For Loops
You can use for loops inside other for loops to iterate over multi-dimensional structures like lists of lists.
matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]]for row in matrix: for num in row: print(num, end=" ") print() # Adds a newline after each rowOutput:
1 2 3 4 5 6 7 8 9
? 5. Looping through a Dictionary
You can loop through the keys and values of a dictionary.
person = {"name": "Alice", "age": 25, "city": "New York"}for key, value in person.items(): print(key, ":", value)Output:
name : Aliceage : 25city : New York
You can also loop through just the keys or just the values:
# Loop through keysfor key in person: print(key)# Loop through valuesfor value in person.values(): print(value)? 6. Using else with For Loops
The else block can be used with a for loop, and it will execute when the loop completes normally (i.e., without encountering a break statement).
for i in range(3): print(i)else: print("Loop finished.")Output:
012Loop finished.Explanation: The
elsepart runs after the loop finishes executing all iterations.
? 7. Break and Continue in For Loops
break: Stops the loop entirely when a certain condition is met.
for i in range(5): if i == 3: break print(i)Output:
012continue: Skips the current iteration and continues with the next one.
for i in range(5): if i == 3: continue print(i)Output:
0124
? 8. For Loop with List Comprehension
A list comprehension is a more compact way to create lists using a for loop. It allows you to iterate over a sequence and return a new list in a single line of code.
squares = [x**2 for x in range(5)]print(squares)Output:
[0, 1, 4, 9, 16]
List comprehensions can also include conditions:
even_squares = [x**2 for x in range(10) if x % 2 == 0]print(even_squares)Output:
[0, 4, 16, 36, 64]
Summary of For Loop Examples:
Basic iteration:
for item in sequenceUsing
range():for i in range(start, stop, step)Nested loops:
for item in sequence: for sub_item in sub_sequenceLooping through a dictionary:
for key, value in dictionary.items()Using
else: Theelseblock runs after the loop finishes (unless abreakis encountered).breakandcontinue: Control the loop’s flow by either stopping or skipping iterations.List comprehensions: Compact syntax to create lists from a sequence.
By using these techniques, you can create efficient and readable loops in Python. Let me know if you need more examples or details! ?