Skip to content

Loops Cheatsheet

First PublishedByAtif Alam
for fruit in ['apple', 'banana', 'cherry']:
print(fruit)

With index using enumerate:

fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(index, fruit) # 0 apple, 1 banana, 2 cherry
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(1, n): # 1 .. n-1 (e.g. split between i-1 and i)
...
for char in "hello":
print(char) # h, e, l, l, o
person = {'name': 'Alice', 'age': 30}
# Keys only
for key in person:
print(f"Key: {key}")
# Keys and values
for key, value in person.items():
print(f"{key}{value}")
# Keys in sorted order
for key in sorted(person):
print(key)
names = ['Alice', 'Bob']
scores = [85, 92]
for name, score in zip(names, scores):
print(f"{name} scored {score}")
with open(filename, 'r') as file:
for line in file:
print(line.rstrip()) # or process line
count = 0
while count < 3:
print("Count:", count)
count += 1