Looping through sequences
A sequence is any type of data that has sequential data inside it. A list is considered a sequence since it contains items in a sequence. A string is also considered a sequence since it contains characters in a sequence. The Python language also offers other sequential data types like tuples and sets, but we won't be diving into those in this course.
All sequence types can be looped through using a loop, either a while
loop or for
loop.
While loops with lists
It's very common to use a loop to process the items in a list, doing some sort of computation on each item.
For example, this while
loop compares the counter variable i
to the list length, and also uses that counter variable i
as the current index:
scores = [80, 95, 78, 92]
total = 0
i = 0
while i < len(scores):
score = scores[i]
total += score
i += 1
That loop sums up all the numbers in a list, storing the result in total
, and stopping after it accesses the last element. Remember, the index of the last element is len(list) - 1)
, not len(list)
. That's why the comparison operator in the loop condition is <
and not <=
. Accidentally using <=
instead will lead to the dreaded off-by-one error. 🙀(At this point, you might be beginning to see why off-by-one errors are so common in programming.)
For loops with lists
There's a much simpler way to iterate through a list: the for
loop.
scores = [80, 95, 78, 92]
total = 0
for score in scores:
total += score
No counter variable, loop condition, or bracket notation needed! Python will start from the beginning of the list and put the current item in the score
loop variable in each iteration, so your loop body can just reference score
.
Looping through strings
Since a string is also a sequential data type, we can also use loops to iterate through a string. Looping over strings is less common than looping over lists, however.
The following loop prints out an integer representing the Unicode code point of each letter in a string:
letters = "ABC"
for letter in letters:
print(ord(letter))
If we iterate through a string with characters that require multiple code points, there will be an iteration for each of those code points.
emoji = "🤷🏽♀️"
for code_point in emoji:
print(ord(code_point))
How many numbers do you think that will print out? Try it and see!
# Try some code here