🐍 For Loop

loop

Good to know

⭐️ for loops iterate over iterables: strings, lists, tuples, sets, dictionaries, ranges, and more.


Looping Through a String

for char in "Giraffe Academy":
    print(char)
# Prints every character one by one

Looping Through a List

Each iteration gives the next element.

animals = ["dog", "cat", "mouse"]
for a in animals:
    print(a)

Looping Through a Range

range(start, end) stops before end.

for number in range(3, 10):
    print(number)
# Prints 3 to 9

Looping With Index (Enumerate)

Gives both the index and the value. Note: You need to use the function enumerate().

names = ["Jim", "Tom", "Sara"]
for index, name in enumerate(names):
    print(index, name)

Looping Through a Dictionary

person = {"name": "Alain", "age": 30}
 
for key in person:
    print(key)
 
for value in person.values():
    print(value)
 
for key, value in person.items():
    print(key, value)

Looping Through a Set

colors = {"red", "green", "blue"}
for c in colors:
    print(c)
# Order is unpredictable (sets are unordered)

Looping Through a 2D List

grid = [
    [1, 2, 3],
    [4, 5, 6]
]
 
for row in grid:
    for col in row:
        print(col)

Loop With Else

else executes only if the loop wasn’t stopped by break.

for n in range(3):
    print(n)
else:
    print("Finished!")