Loops Cheatsheet
for over a list
Section titled “for over a list”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 cherryfor with range
Section titled “for with range”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 over a string
Section titled “for over a string”for char in "hello": print(char) # h, e, l, l, ofor over a dictionary
Section titled “for over a dictionary”person = {'name': 'Alice', 'age': 30}
# Keys onlyfor key in person: print(f"Key: {key}")
# Keys and valuesfor key, value in person.items(): print(f"{key} → {value}")
# Keys in sorted orderfor key in sorted(person): print(key)Parallel iteration with zip
Section titled “Parallel iteration with zip”names = ['Alice', 'Bob']scores = [85, 92]
for name, score in zip(names, scores): print(f"{name} scored {score}")Reading a file line by line
Section titled “Reading a file line by line”with open(filename, 'r') as file: for line in file: print(line.rstrip()) # or process linewhile loop
Section titled “while loop”count = 0while count < 3: print("Count:", count) count += 1