What is range(len()) about?

Hi,
What’s the difference in between the following concepts?

In this given case they produce the same result, but they are not always interchangeable. I don’t think that range(len()) was explained in theory courses, but it is common in Practice mode and everytime I see it I feel lost. So here’s the question: when it’s better to use range(len)) functions? I wonder what the arguments are for using range(len)) instead of this concept:
a_list = ["a ", "b ", "c"]

for index in a_list:
    print(index)

Hi tomek.skrill1

Welcome to the community!

The documentation for range() function can be found here.
It produces a list of numbers. In the above code, len(a_list) is 3. So the output of range(3) would be

0
1
2

So, now our code can be interpreted as for index in [0, 1, 2]:
Inside the for loop, we will have, a_list[0], a_list[0], a_list[0], and for this the output would be a, b, c respectively.

For the next code snippet, the for loop can be interpreted as for index in ["a", "b", "c"]:
Hence the output is a, b, c.

You can refer this, for better understanding and practice a few simple examples.

Hope this helps.
Thanks.

1 Like

I am not sure if i understand your question properly but here is my answer if it helps

Using first scenario we can change original list [So if have any scenario which required change in list during iteration we can use range for indexing other second is fine]

a_list = ['a', 'b', 'c']
for index in range(len(a_list)):
    a_list[index] = a_list[index] + a_list[index]
    print(a_list[index])
    
print(a_list)

aa
bb
cc
['aa', 'bb', 'cc']

And for second scenario it has local scope so whatever you change stay within loop. It does not impact original list.

a_list = ['a', 'b', 'c']
for index in a_list:
    index = index + index
    print(index)
    
print(a_list)

aa
bb
cc
['a', 'b', 'c']
1 Like

Thank you for your responses.

I’m still not sure regarding the practical difference between those two. For example below, why can’t we use here for row in range(len(rows)):

> from csv import reader
> read the CSV file
> file = open("users.csv")
> file_reader = reader(file)
> rows = list(file_reader)[1:] # ignore column headers
> file.close()
> 
> name_to_email = {}
> 
> for row in rows: <------- why not for row in range(len(rows)):
>     get the name and the email from the row
>     name = row[0]
>     email = row[1]
>    
>     name_to_email[name] = email

And why here we use range(len()):

values1 = [80, 109, 111, 109, 94, 93, 108, 107, 81, 111, 101, 114, 102, 81, 107, 120, 108, 92, 113, 119, 97]
values2 = [97, 119, 113, 92, 108, 120, 107, 81, 102, 114, 110, 111, 81, 107, 108, 93, 94, 109, 111, 109, 80]
 

is_reversed = True


for i in range(len(values1)): <--------- why can't we use here for i in values1:`

if values1[i] != values2[len(values1)- i - 1]:
                is_reversed = False

So I still wonder if there is a rule that explains: We use for x in range(len(list_name)): if we want to do x,y,z. And we use for x in list_name: if we want to do a,b,c?

Hi @tomek.skrill1

I think the major difference will be visible when you are dealing with a list of list.

When you are using range(len( list) ) it first returns the length of the list and then creates a sequence starting from zero. In your first example, it will be (0,1,2). So when you are dealing with range(len()) you are dealing with integers.

But when you use for x in list_name you are iterating through each elements of the list.
list = ['a','b','c']
for i in range(len(list)) would return i= 0,1,2 in each iteration
while
for i in list would return i=a,b,c in each iteration.

So we use for i in range(len()) when you want to known the length of the list and iterate that many number of time

and we use for i in list when we want to iterate through each elements of the list.

Did this answer your question?
`

1 Like

Ok, what about the following piece of code where we need to create a dictionary from two lists:

keys = ['Katherine Freeman', 'Tammy Gonzalez', 'Robin Matthews', 'Sherry Farrell', 'Emma Graves', 'Tina Brown', 'George Owens', 'Ronald Ball']
values = ['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]']

my_dict = {}

for key in range(len(keys)):
    my_dict[keys[key]] = values[key]

In this case range(len)) is not used just to know the length of the list or just to iterate the many number of time. So why was it used? At the same time time for key in keys: doesn’t seem to work even though we do want to iterate through each element of the list. Why is it so?

Hi @tomek.skrill1

Here it is used to find the length of the list and thus to find the index of the list, and to access the index of the list and iterates through it. You can see keys and values are lists and are indexed from 0 to len(list)-1

1 Like

Thank you guys! Finally it clicked in my brain. I’m a little bit embarassed that it took it so long, but better late than never :smile:

1 Like