To move through each item in a list, we use for loops
for <temporary variable> in <list>:
<action>
For example
students = ['Hanna', 'Jake', 'Jane']
for name in students:
print(name)
#Output:
Hanna
Jake
Jane
The while loop is like a repeated if statement. The code is executed over and over again, as long as the condition is True. Have another look at its recipe.
while condition:
# code block to be executed
For example
nums = [0, 1, 2, 3]
i = 0
while i < len(nums):
print(i)
i += 1
# Output
0
1
2
3
To iterate through a list of certain length, we should use range
.
range
takes in a number n as input, and returns a list from 0 to n-1.
For example
greetings = "Hello"
for i in range(2):
print(greetings)
# Output:
Hello
Hello
You can stop a for loop from inside the loop by using break
.
When the program hits a break statement, control returns to the code outside of the for loop.
students = ['Hanna', 'Jake', 'Jane', 'April', 'Niles']
print("Find April on the list!")
for name in students:
if name == 'April':
print(name)
break
print("End of search!")
// Output:
Find April on the list!
April
End of search!
If you want to skip some values while iterating through lists, we can use continue
keyword.
For example, we’d like to print out all of the numbers in a list, unless they’re negative.
We can use continue to move to the next i in the list:
positive_list = [10, 4, -1, 2, -5, 7, 3, -9]
for i in positive_list:
if i < 0:
continue
print(i)
if we have a list made up of multiple lists, we canloop through all of the individual elements by using nested loops.
For example, create a function named exponents() return a new list containing every number in bases raised to every number in powers.
def exponents(bases, powers):
new = []
for i in bases:
for j in powers:
new.append(i**j)
return new
Python list comprehensions provide a concise way for creating lists.
Syntax:
lst = [EXPRESSION for ITEM in LIST <if CONDITIONAL>]
For example
# List comprehension for the squares of all even numbers between 0 and 9
result = [x**2 for x in range(10) if x % 2 == 0]
print(result)
# [0, 4, 16, 36, 64]
If you accidentally creates an infinite loop while developing on your own machine, you can end the loop by using control + c
to terminate the program.