Codecademy Forums

Why do we have to use this code in the for loop?

Hi
Why do this have to be included in the for loop, in this exercise?
More specifically I dont understand the point of having the “range” in there.

range(len(lst1)):

https://www.codecademy.com/courses/learn-python-3/lessons/python-functions-loops-cc/exercises/same-index?action=resume_content_item

for example:

same_values([5, 1, -10, 3, 3], [5, 10, -10, 3, 5])

should return [0, 2, 3] given the values at those indices are the same. Which is why we use range, to get the indices, how else where you going to do that?

1 Like

Hi

I think I dont understand the difference between the range function and the lenght function. Isn`t it enough to just use the len-function, or just the range-function. Why do we have to use both?

1 Like

If we just use len(lst1):

>>> lst1 = ["alpha","beta","gamma"]
>>> for i in len(lst1):
	print(i)
	
Traceback (most recent call last):
  File "<pyshell#37>", line 1, in <module>
    for i in len(lst1):
TypeError: 'int' object is not iterable
>>> 

As you can see, this is because the int type is not iterable.

We can, however, plug the int which comes back from len - i.e. the length of the list, which is 3 in this example case - into the range function as the maximum value, and get an iterable sequence for our for loop:

>>> lst1 = ["alpha","beta","gamma"]
>>> for i in range(len(lst1)):
	print(i)
	print(lst1[i])

	
0
alpha
1
beta
2
gamma
>>> 

You can use range on its own, sure, but let’s say your for loop needs to iterate over a list of 5 items and you use range(10). Your loop will work fine for the first 5 iterations, because the values of range up to then will have been 0,1,2,3,4… As soon as it tries to access your_list[5], the non-existent 6th item, you’ll get an IndexError.

Using range(len(your_list)) means that the values in range match up to the number of items in your list, regardless of how big the list is at the start of the loop.

That help? :slight_smile:

1 Like

Aha understood

On more question

The len function returns the length of the function, and the range function returns the index value?

example list with numbers: 1, 2, 3 ,4, 5
Len function: 5
range function: 4

Not quite.

Let’s say we have a list, like so:

shopping_list = ["apples","bread","laundry detergent","wine"]

The len function returns the length of the list, in this case, so len(shopping_list) = 4, because there’s 4 items in my list.

We can now do range(len(shopping_list)), which is the same as range(4), which will generate the sequence 0,1,2,3. This corresponds to the indices of the four items in shopping_list.

Essentially, by doing range(len(shopping_list)), I can make shopping_list have as many items as I want, and I’ll always get a sequence of numbers which is long enough to make sure my for loop covers off every item.

Does that make sense? :slight_smile:

2 Likes