x = ["a", "b", "c", "d"]
for a in x:
print(a, a.upper())a A
b B
c C
d D
Let’s look at commonly used iteration patterns in Python.
This is the most common pattern and you’ve seen it already.
We could use the same pattern with a list comprehension as well.
We can use the range function to iterate over a sequence of numbers.
And the same pattern as a list comprehension:
The built-in function zip can be used to iterate over two lists togetger.
There would be times when we need to use both the index and the element when iterating over a list. While it is possible to use range(len(x)) to iterate over the index and use the index to access the element, that is quite clumsy. Python provides a built-in function called enumerate to address this.
Let’s say we have a list of chapter titles.
And we want to print the chapter number and title together.
Chapter 0 Getting Started
Chapter 1 Functions
Chapter 2 Lists
Chapter 3 Dictionaries
We may want the chapter number to start from 1. We could print i+1 instead of i.
Chapter 1 Getting Started
Chapter 2 Functions
Chapter 3 Lists
Chapter 4 Dictionaries
Or we can just tell enumerate to start counting from 1 instead of 0.
Chapter 1 Getting Started
Chapter 2 Functions
Chapter 3 Lists
Chapter 4 Dictionaries
We can also use this pattern in list comprehensions.
Problem: write a function vector_add to add two vectors.