Lists and Loops

lists and loops

Lists and loops

Video Transcript

In this section, we're going to use loops to iterate over lists. There are two main ways to loop over a list.
The first way uses the in keyword. in has two jobs: it can be used as a condition to check if a list contains some value, or it can be used to iterate over the elements of a list one at a time. This method is convenient if we just want to look at each of the elements in a list without changing them:
numbers = [6, 8, 2, 9, 7]

print(6 in numbers) # True
print(0 in numbers) # False

for number in numbers:
# prints 6, 8, 2, 9, 7
The second way uses the len function to get the number of elements in the list, and then range to loop over the numbers 0 to len(list) - 1, which gives the index. Because we have access to the index, we can use this method whenever we want to change the values in a list:
numbers = [6, 8, 2, 9, 7]

for i in range(len(numbers)):
  numbers[i] = numbers[i] ** 2

# [36, 64, 4, 81, 49]
Last section Next section