Python for Loop
A for loop takes values one at a time out of something that holds several, such as a list or a string, and repeats the code below it. Unlike in other languages, you don't increase an index yourself, and the loop ends on its own when there is nothing left to take. The code to repeat is grouped by indentation.
for variable in iterable:
code to repeat
Looping over a list and a string
Put a list after in and its values go into the variable one at a time, from the front. Put a string there and you get one character at a time.
fruits = ["apple", "kiwi", "plum"]for fruit in fruits: print(fruit, len(fruit)) for ch in "abc": print(ch.upper())print("done")apple 5 kiwi 4 plum 4 A B C done
Only the indented lines repeat. print("done"), where the indentation has ended, runs just once after the loop is all finished.
Repeating a set number of times and collecting a value
When the number of repetitions is fixed, use for together with range. Set a variable to 0 before the loop and add to it on every iteration, and you get the total.
n = 5total = 0for i in range(1, n + 1): total += i print(i, total)print("sum:", total)1 1 2 3 3 6 4 10 5 15 sum: 15
Taking two values together
When the values are pairs (tuples), you can separate the variables with a comma and unpack them in one go. To loop over two lists side by side, pair them up with zip.
pairs = [("kim", 90), ("lee", 75)]for name, score in pairs: print(name, score) names = ["a", "b", "c"]points = [1, 2, 3]for name, p in zip(names, points): print(name * p)kim 90 lee 75 a bb ccc
When the two lists have different lengths, zip stops at the shorter one.
Nested for loops
Put a for inside a for, and the inner loop runs from start to finish for every single iteration of the outer one. Use it when you work with tables or grids.
for row in range(1, 4): line = "" for col in range(1, 4): line += str(row * col) + " " print(line)1 2 3 2 4 6 3 6 9
A for in one line: list comprehensions
Building a new list while looping with for can be written in one line inside square brackets. Add an if at the end and it picks only the values that meet the condition.
nums = [1, 2, 3, 4, 5]squares = [x * x for x in nums]evens = [x for x in nums if x % 2 == 0]print(squares)print(evens)[1, 4, 9, 16, 25] [2, 4]
Common mistakes
Leaving out the colon at the end of the line
for i in range(3)
print(i)
→ SyntaxError: expected ':'
The for line must end with :: for i in range(3):.
Not indenting the code to repeat
for i in range(3):
print(i)
→ IndentationError: expected an indented block after 'for' statement on line 1
Indent the line below for with four spaces. If there are several lines to repeat, give them all the same depth.
Trying to change the list by assigning to the loop variable
nums = [1, 2, 3]
for x in nums:
x = x * 2
print(nums)
→ Still [1, 2, 3], not [2, 4, 6]
x is only a name attached to the value that was taken out, so assigning a new value to it does not change the item in the list. Build a new list with nums = [x * 2 for x in nums], or change it by index, as in nums[i] = nums[i] * 2.
Removing values from the list you are looping over
nums = [1, 2, 2, 3]
for x in nums:
if x == 2:
nums.remove(x)
print(nums)
→ You thought you removed every 2, but you get [1, 2, 3] — one is left
Removing a value pulls the values after it forward by one position, so the very next value gets skipped. Build a new list with only what you want to keep: nums = [x for x in nums if x != 2].