More List Functionality
Continue¶
Using continue makes the loop skip whatever else is there in the tabbed code and move on to the next iteration of the loop. Below you will see how normally the code prints the variable x being iterated over followed by three lines of XX. However, if the variable x is greater than 2 it skips the rest of the code and moves to the next iteration.
#Continue forces the loop to go to the top of the loop with the next iterable
#Notice how once x>2 we don't see XX printed out anymore
for x in range(0,5):
print(x)
if x>2:
continue
print("XX")
print("XX")
print("XX")
You are able to iterate over more than just a range. For example, lists are valid things to iterate over. Below we define a list and use a loop for all the values in it.
#Instead of a range you can also iterate over a list
l = [1,5,10,20]
for x in l:
print(x)
You may recall from an earlier lesson how we used zip. You can use it here to iterate over two iterables at the same time. In the code below, we are going to do three iterations. One where x=1, y=2, one where x=2, y=6, and finally one where x=3, y=10.
#Zip let's you iterate through lists together
l1 = [1,2,3]
l2 = [2,6,10]
for x,y in zip(l1,l2):
print(x*y)
When using nested lists, you will end up iterating over the inner lists. In the code below, the nested list has a length of 3 where each element is a list. Iterating over it will print out each of these inner lists.
#If you have a nested list you can iterate through the inner lists
l = [[1,2,3],[4,5,6],[7,8,9]]
for x in l:
print(x)
You could also iterate over the inner list by iterating over that variable x from the for loop.
#But if you wanted the inner numbers you would use a second loop to go through your iterable x
for x in l:
for y in x:
print(y)