2020-06-24
|~2 min read
|309 words
The following post is inspired by Trey Hunner’s great post on looping with indexes in Python.
What’s below:
Python’s looping reads almost like English. If we want to see every character in a string or every number in a range, we can do something as simple as a for in
:
string = "ABCDEFG"
nums = range(10)
for c in string:
print(c)
for num in nums:
print(num)
Ranges start to be interesting if we want to loop over lists, or create lists from other iterables.
names=["Stephen","Kate","Finn","Magpie"]
for i in range(len(names)):
print(names[i])
Here i
is the index of the list names
, which is then used to access the value in the print statement.
Of course, in Python, this isn’t necessary:
names=["Stephen","Kate","Finn","Magpie"]
for name in range(names):
print(name)
That’s some sweet syntactic sugar right there!
Learning about Python’s enumerate
package is when I started to get excited! Sometimes, you want access to the actual index.
We could do the trick above where we convert the iterable with the len()
and then use both the index and the value, but we don’t have to.
Python’s enumerate
, a built-in function:
names=["Stephen","Kate","Finn","Magpie"]
for index, name in enumerate(names):
print(f"{name} is in position {index}")
So, with enumerate
we can access both the index and the value. That means that we could, in theory map it to a separate list.
For example:
names=["Stephen","Kate","Finn","Magpie"]
ages=["30","???","2.5","0"]
for index, name in enumerate(names):
print(f"{name} is {ages[index]} years old.")
This works, but it’s a little awkward.
We can use Python’s zip
function for this:
names=["Stephen","Kate","Finn","Magpie"]
ages=["30","???","2.5","0"]
for name, age in zip(names, ages):
print(f"{name} is {age} years old.")
Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!