Iterating through a list with a for loop

Hello, guys!

I advanced now at the strings part. However, there is a thing I’m still unsure of and looks a bit confusing, from a few lessons back. I looked on the internet on multiple websites and still haven’t found a clearer approach to my dilemma. Here it is:

I have the following list:

cat = [1, 3, 5, 7, 9] 

and I decide to iterate through all the elements in the list and make X action result from that iteration (I chose the for loop):

for i in range(len(cat)): 
for i in cat: 

The thing is the output is the same:

I looke in the documentation and on many other websites. They say the range is used if one desires to iterate only on a portion of the list from let’s say index 4 until the end of the list.

My questions are:

  1. Is this the only reason why we use range(len(list)) over just naming the list?
  2. If we want to refer to all the elements and iterate through all the list and not just a portion, which one is preferable and does it make a difference?

Thank you!

range gives us indices/indexes, this is useful if we need to mutate elements in the list:

cat = [1, 3, 5, 7, 9] 
for i in range(len(cat)): 
   cat[i] *= 2 # multiple each element in the list


if you just want to print each element, i would recommend:

for i in cat: 

to get the elements from the list directly.

i think i cover this in explaining point 1?

1 Like

Thank you a lot, @stetim94!