Practice Problem: List and For Loops -- Problem 5

Exercize: use a for loop to add 1 to each value in the list.
values = [16, 1, 7, 2, 19, 12, 5, 20, 2, 10, 10, 14, 17, 14, 1, 16, 19, 7, 9, 19]

Answer
for x in range(len(values)):
values[ x ] += 1

Screen Link: https://app.dataquest.io/m/1009/lists-and-for-loops-practice-problems/5/incrementing-all-elements

My Question:
Hi! I am wondering why the ‘len()’ is needed in the for loop? I am still grasping all of the intricacies of what each built-in function does. I was under the impression ‘len()’ only returned the length (number of characters). So why is it necessary for this function to work?

Thanks!

I would recommend starting to get used to exploring the documentation at this point.

You can check out the documentation for len() and range() and then see what you can understand yourself first. If something isn’t clear, ask follow-up questions.

Hi @heather.emoto, welcome to the community!

Let’s look at the code again and break it down:

for x in range(len(values)):
values[x] += 1

For this exercise, we input one argument inside the range() function. Note that the range() function can actually accept up to three arguments. In this case, since we indicated one argument, then range(N) will iterate or cycle over all integers from 0 to N-1 since the end-point of the range is non-inclusive.

If we look at a simple range loop that prints values:

for r in range(5):
    print(r)

Output:
0
1
2
3
4

I was under the impression ‘len()’ only returned the length (number of characters). So why is it necessary for this function to work?

I think your confusion arises from being only familiar with the len() function being applied to strings, where it will indeed return the number of characters for that string. However, note that the len() function when applied to a list such as values will return the number of elements within that list. In this case, len(values) = 20.

This means that the loop

for x in range(len(values)):
   print(values[x])

is pretty much equivalent to:

for x in range(20):
   print(values[x])

The loop will iterate from values[0] (the first item in the list since indexing is zero-based) up to values[19] (the last item in the the list). The loop ends at 19 because the end-point (20) is non-inclusive in the range function.

We use the len(values) as an argument to save ourselves from the task of manually counting how many elements we have to loop over when using the range() function.

It’s always a good idea to check the documentations if they’re available. Here’s a link to documentation for Python’s built-in functions, which includes len() and range(), among others.

1 Like

This was incredibly helpful. Thank you so much!