Python has a for loop which is allows us to step through each element in an iterable (generally anything that defines __iter__ or __getitem__ such as files, lists, tuples, etc.).
First let’s go through an example of a for loop
for i in range(10): print(str(i))
When run, this code produces the following output
0 1 2 3 4 5 6 7 8 9
Let’s discuss how this works. Our loop begins with the keyword
for followed by a variable or variables. After the variable, we have the
in keyword followed by an iterable. The loop continues until there are no more items in the iterable.
In our example, the iterable is the
range function. So when we have
range(10) we are making a sequence of ten numbers 0-9. Everytime
range produces a number, it gets assigned to the variable
i. We then use
print(str(i)) to print the value of
i to the console.
Here is another demonstration of the for loop, this time using a list
names = ['Bob', 'Tina', 'Gene', 'Linda'] for name in names: print(name)
Lists implement the correct protocals that allow them to be used in
for loops. In this case, we populate a list with some names. Everytime the loop executes, the name variable is updated with the next name in the list. We then print the name to the console.
for loop let’s us have more than one variable in the loop.
names = [['Bob', 'Belcher'], ['Tina', 'Belcher'], ['Gene', 'Belcher'], ['Linda', 'Belcher']] for fname, lname in names: print(fname, ' ', lname)
Keep in mind that when you do this, your update variables need to match the number of variables in your sequence. So if we had three variables here, we would get an exception.
7 thoughts on “For Loops—Python”
Nice explanation.. Specially when it has Bob’s burger in it! 🙂
LikeLiked by 1 person
This is very helpful, thank you! I just learned about the for and in keywords today to use loops on lists. Your explanation is clear and fun! 🙂
Awesome! I’m glad to hear that my explanation on loops is helpful to you! Feel free to write me on other topics that you need help with. I tutor Python so I’m glad to help!
That’s great, thank you! If I have questions, I’ll let you know! 🙂
LikeLiked by 1 person