Certainly! Below are 100 examples of loop structures in Python, ranging from basic to advanced. Each example includes an explanation and the expected output.
1. Basic `for` loop
for i in range(5):
print(i)
Explanation: This loop iterates over the numbers 0 to 4 and prints each number.
Output:
0
1
2
3
4
2. `for` loop with a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Explanation: This loop iterates over each element in the fruits
list and prints it.
Output:
apple
banana
cherry
3. `while` loop
count = 0
while count < 5:
print(count)
count += 1
Explanation: This loop continues to execute as long as count
is less than 5, printing the current value of count
and then incrementing it.
Output:
0
1
2
3
4
4. Nested `for` loops
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")
Explanation: This loop demonstrates nested loops, where the inner loop runs completely for each iteration of the outer loop.
Output:
i=0, j=0
i=0, j=1
i=1, j=0
i=1, j=1
i=2, j=0
i=2, j=1
5. `for` loop with `else`
for i in range(3):
print(i)
else:
print("Loop finished")
Explanation: The else
block is executed after the loop completes normally (i.e., without a break
statement).
Output:
0
1
2
Loop finished
6. `while` loop with `else`
count = 0
while count < 3:
print(count)
count += 1
else:
print("Loop finished")
Explanation: Similar to the for
loop, the else
block is executed after the while
loop completes normally.
Output:
0
1
2
Loop finished
7. `break` statement in `for` loop
for i in range(5):
if i == 3:
break
print(i)
Explanation: The loop breaks when i
equals 3, so only numbers 0, 1, and 2 are printed.
Output:
0
1
2
8. `continue` statement in `for` loop
for i in range(5):
if i == 3:
continue
print(i)
Explanation: The loop skips the iteration when i
equals 3, so numbers 0, 1, 2, and 4 are printed.
Output:
0
1
2
4
9. `for` loop with `enumerate`
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")
Explanation: The enumerate
function provides both the index and the value of each element in the list.
Output:
Index 0: apple
Index 1: banana
Index 2: cherry
10. `for` loop with `zip`
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
Explanation: The zip
function pairs elements from two lists together, allowing iteration over both simultaneously.
Output:
Alice is 25 years old
Bob is 30 years old
Charlie is 35 years old
11. `for` loop with dictionary
person = {"name": "Alice", "age": 25, "city": "New York"}
for key, value in person.items():
print(f"{key}: {value}")
Explanation: The items()
method returns key-value pairs from the dictionary, which can be iterated over.
Output:
name: Alice
age: 25
city: New York
12. `for` loop with `range` step
for i in range(0, 10, 2):
print(i)
Explanation: The range
function is used with a step of 2, so it prints even numbers from 0 to 8.
Output:
0
2
4
6
8
13. `for` loop with negative step
for i in range(5, 0, -1):
print(i)
Explanation: The range
function is used with a negative step, so it counts down from 5 to 1.
Output:
5
4
3
2
1
14. `for` loop with `reversed`
fruits = ["apple", "banana", "cherry"]
for fruit in reversed(fruits):
print(fruit)
Explanation: The reversed
function is used to iterate over the list in reverse order.
Output:
cherry
banana
apple
15. `for` loop with `sorted`
numbers = [3, 1, 4, 1, 5, 9]
for number in sorted(numbers):
print(number)
Explanation: The sorted
function is used to iterate over the list in sorted order.
Output:
1
1
3
4
5
9
16. `for` loop with `set`
unique_numbers = {1, 2, 2, 3, 4, 4, 5}
for number in unique_numbers:
print(number)
Explanation: Sets automatically remove duplicates, so the loop iterates over unique elements.
Output:
1
2
3
4
5
17. `for` loop with `filter`
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
for number in even_numbers:
print(number)
Explanation: The filter
function is used to filter out even numbers from the list.
Output:
2
4
6
18. `for` loop with `map`
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(lambda x: x ** 2, numbers)
for number in squared_numbers:
print(number)
Explanation: The map
function applies a lambda function to each element in the list, squaring each number.
Output:
1
4
9
16
25
19. `for` loop with list comprehension
squares = [x ** 2 for x in range(5)]
for square in squares:
print(square)
Explanation: List comprehension is used to create a list of squares, which is then iterated over.
Output:
0
1
4
9
16
20. `for` loop with generator expression
squares = (x ** 2 for x in range(5))
for square in squares:
print(square)
Explanation: A generator expression is used to create an iterator of squares, which is then iterated over.
Output:
0
1
4
9
16
21. `for` loop with `itertools.count`
import itertools
for i in itertools.count(start=0, step=2):
if i > 8:
break
print(i)
Explanation: The itertools.count
function generates an infinite sequence, which is controlled by a break
statement.
Output:
0
2
4
6
8
22. `for` loop with `itertools.cycle`
import itertools
colors = ["red", "green", "blue"]
for color in itertools.cycle(colors):
if color == "blue":
break
print(color)
Explanation: The itertools.cycle
function cycles through the list indefinitely until a break
statement is encountered.
Output:
red
green
23. `for` loop with `itertools.repeat`
import itertools
for i in itertools.repeat("Hello", 3):
print(i)
Explanation: The itertools.repeat
function repeats the specified value a given number of times.
Output:
Hello
Hello
Hello
24. `for` loop with `itertools.chain`
import itertools
list1 = [1, 2, 3]
list2 = [4, 5, 6]
for number in itertools.chain(list1, list2):
print(number)
Explanation: The itertools.chain
function is used to iterate over multiple sequences as if they were a single sequence.
Output:
1
2
3
4
5
6
25. `for` loop with `itertools.product`
import itertools
for x, y in itertools.product([1, 2], ["a", "b"]):
print(x, y)
Explanation: The itertools.product
function generates the Cartesian product of the input iterables.
Output:
1 a
1 b
2 a
2 b
26. `for` loop with `itertools.permutations`
import itertools
for perm in itertools.permutations([1, 2, 3], 2):
print(perm)
Explanation: The itertools.permutations
function generates all possible permutations of the specified length.
Output:
(1, 2)
(1, 3)
(2, 1)
(2, 3)
(3, 1)
(3, 2)
27. `for` loop with `itertools.combinations`
import itertools
for comb in itertools.combinations([1, 2, 3], 2):
print(comb)
Explanation: The itertools.combinations
function generates all possible combinations of the specified length.
Output:
(1, 2)
(1, 3)
(2, 3)
28. `for` loop with `itertools.combinations_with_replacement`
import itertools
for comb in itertools.combinations_with_replacement([1, 2, 3], 2):
print(comb)
Explanation: The itertools.combinations_with_replacement
function generates combinations where elements can be repeated.
Output:
(1, 1)
(1, 2)
(1, 3)
(2, 2)
(2, 3)
(3, 3)
29. `for` loop with `itertools.groupby`
import itertools
data = [("a", 1), ("a", 2), ("b", 3), ("b", 4)]
for key, group in itertools.groupby(data, lambda x: x[0]):
print(key, list(group))
Explanation: The itertools.groupby
function groups consecutive elements based on a key function.
Output:
a [('a', 1), ('a', 2)]
b [('b', 3), ('b', 4)]
30. `for` loop with `itertools.islice`
import itertools
for i in itertools.islice(range(10), 2, 6):
print(i)
Explanation: The itertools.islice
function is used to slice an iterator, similar to slicing a list.
Output:
2
3
4
5
31. `for` loop with `itertools.takewhile`
import itertools
for i in itertools.takewhile(lambda x: x < 5, range(10)):
print(i)
Explanation: The itertools.takewhile
function takes elements from the iterator as long as the condition is true.
Output:
0
1
2
3
4
32. `for` loop with `itertools.dropwhile`
import itertools
for i in itertools.dropwhile(lambda x: x < 5, range(10)):
print(i)
Explanation: The itertools.dropwhile
function drops elements from the iterator as long as the condition is true, then yields the rest.
Output:
5
6
7
8
9
33. `for` loop with `itertools.tee`
import itertools
iter1, iter2 = itertools.tee(range(3))
for i in iter1:
print(i)
for i in iter2:
print(i)
Explanation: The itertools.tee
function creates multiple independent iterators from a single iterable.
Output:
0
1
2
0
1
2
34. `for` loop with `itertools.zip_longest`
import itertools
list1 = [1, 2, 3]
list2 = ["a", "b"]
for x, y in itertools.zip_longest(list1, list2, fillvalue="N/A"):
print(x, y)
Explanation: The itertools.zip_longest
function zips iterables of unequal length, filling missing values with a specified fill value.
Output:
1 a
2 b
3 N/A
35. `for` loop with `itertools.starmap`
import itertools
data = [(2, 5), (3, 2), (10, 3)]
for result in itertools.starmap(pow, data):
print(result)
Explanation: The itertools.starmap
function applies a function to the elements of an iterable, where each element is a tuple of arguments.
Output:
32
9
1000
36. `for` loop with `itertools.accumulate`
import itertools
data = [1, 2, 3, 4, 5]
for result in itertools.accumulate(data):
print(result)
Explanation: The itertools.accumulate
function returns accumulated sums (or other binary function results) of the input iterable.
Output:
1
3
6
10
15
37. `for` loop with `itertools.compress`
import itertools
data = ["a", "b", "c", "d"]
selectors = [True, False, True, False]
for result in itertools.compress(data, selectors):
print(result)
Explanation: The itertools.compress
function filters elements from the data iterable using the corresponding boolean values in the selectors iterable.
Output:
a
c
38. `for` loop with `itertools.filterfalse`
import itertools
data = [1, 2, 3, 4, 5]
for result in itertools.filterfalse(lambda x: x % 2 == 0, data):
print(result)
Explanation: The itertools.filterfalse
function filters elements from the iterable where the condition is false.
Output:
1
3
5
39. `for` loop with `itertools.pairwise` (Python 3.10+)
import itertools
data = [1, 2, 3, 4]
for a, b in itertools.pairwise(data):
print(a, b)
Explanation: The itertools.pairwise
function returns successive overlapping pairs from the iterable.
Output:
1 2
2 3
3 4
40. `for` loop with `itertools.batched` (Python 3.12+)
import itertools
data = [1, 2, 3, 4, 5, 6]
for batch in itertools.batched(data, 2):
print(batch)
Explanation: The itertools.batched
function returns batches of the specified size from the iterable.
Output:
(1, 2)
(3, 4)
(5, 6)
41. `for` loop with `itertools.cycle` and `itertools.islice`
import itertools
colors = ["red", "green", "blue"]
for color in itertools.islice(itertools.cycle(colors), 5):
print(color)
Explanation: The itertools.cycle
function is combined with itertools.islice
to limit the number of iterations.
Output:
red
green
blue
red
green
42. `for` loop with `itertools.repeat` and `itertools.islice`
import itertools
for i in itertools.islice(itertools.repeat("Hello"), 3):
print(i)
Explanation: The itertools.repeat
function is combined with itertools.islice
to limit the number of repetitions.
Output:
Hello
Hello
Hello
43. `for` loop with `itertools.chain` and `itertools.islice`
import itertools
list1 = [1, 2, 3]
list2 = [4, 5, 6]
for number in itertools.islice(itertools.chain(list1, list2), 4):
print(number)
Explanation: The itertools.chain
function is combined with itertools.islice
to limit the number of elements iterated over.
Output:
1
2
3
4
44. `for` loop with `itertools.product` and `itertools.islice`
import itertools
for x, y in itertools.islice(itertools.product([1, 2], ["a", "b"]), 3):
print(x, y)
Explanation: The `it