In Python (and really general programming), loops are a fundamental building block of data analysis and computer science in general. The for
loop is an extremely popular loop should be mastered by all practioners.
The Python For loop will iterate through an object and “do something” to each item. The loop will stop when it reaches the end of your iterable, or you tell it to stop.
for i in range(3): print (i) >>> 0 >>> 1 >>> 2
Python For Loop Continue
You can ‘continue’ or stop the current iteration of the loop via the continue
command. Python continue
will move on to the next item in your script without running the remaining code. See an example below.
For Loop Break
Python break
will ‘break’ your for loop and stop it all together. This means your for loop will stop executing and not iterate on any more items.
This is especially useful when you’re running your for loop until a certain condition. When that condition is met, you can stop your loop and move on. See an example below.
Let’s take a look at a python for code sample
Python For Loop¶
Within general programming, loops are a fundamental building block. Few loops are as nice to read as the python for loop. It reads like a sentence.
"For each piece in the whole: Do something with the piece"
Let's look at a few examples
for i in [1,2,3,4]:
print (i)
for i in "Bob":
print (i)
dict_ = {"Key1" : "Value1", "Key2" : "Value2", "Key3" : "Value3"}
for i in dict_:
print (i, dict_[i])
# You need to make sure you're iterating through an iterable
for i in 3:
print (i)
One thing you'll need to watch out for, is when you're mutating (changing) the thing you're iterating through.
In this example. For each loop we do, we are 'popping' (taking an item off the end) the list. Notice how the list stops short
my_list = [1,2,3,4,5,6,7]
for num in my_list:
print (num)
my_list.pop()
A handy trick is to 'enumerate' what you're iterating through. This means counting which item you're on in your list. If you enumerate, a tuple will be returned to you, so you can have two variables after your 'for.' I usually call my first one 'i' for index.
my_list = ["Sally", "Frank", "Ted", "Katie"]
for i, num in enumerate(my_list):
print (i, num)
You can 'continue' a for loop which means 'skip the rest of the code in this loop and move on to the next item'
for i in range(6):
if i == 3:
continue
print (i)
Or you can stop your loop altogether via the "break" command.
for i in range(6):
if i == 3:
break
print (i)
Check out more Python Vocabulary on our Glossary Page