I dont understand whats going on

https://www.codecademy.com/paths/computer-science/tracks/cspath-flow-data-iteration/modules/dspath-python-loops/projects/carlys-clippers

So I’m on step 8 of this project, I managed to do it but I don’t really understand what I’ve done. Here is step 8 as well as step 7 for context:

7) Carly really wants to make sure that Carly’s Clippers is a profitable endeavor. She first wants to know how much revenue was brought in last week.

Create a variable called  `total_revenue`  and set it to  `0` .

8) Use a  `for`  loop to create a variable  `i`  that goes from  `0`  to  `len(hairstyles)`

Here is the code I created:

total_revenue = 0

for i in range(len(hairstyles)):

  total_revenue += prices[i]

  total_revenue += last_week[i]

I had to use a hint for the first part of the code

for i in range(len(hairstyles)):

I dont understand what I’m doing here or why

Why am I getting the length of “hairstyles” and then getting the range of the length?
Is it because i’m iterating through the range of indices in the variable? If so, couldn’t I have just done

for i in hairstyles:

Doesn’t that have the same effect?

The best way for you to understand is to see the effects of both:

try this

for i in hairstyles:
    print(i)
for i in range(len(hairstyles)):
    print(i)

# and for fun!
for i in range(0, len(hairstyles), -1):
    print(i)
5 Likes
for i in range(len(hairstyles)):
  print(prices[i])

This iterates for every item in hairstyles and prints the prices variable every iteration

for i in hairstyles:
  print(prices[i])

This gives a TypeError: list indices must be integers or slices, not str

So basically I’m converting the string list to an index list

When I try to do this:

for i in len(hairstyles)):

It says

TypeError: 'int' object is not iterable

So how does converting the len into a range make it iterable?

should be range(len(hairstyles)) to not get the type error

one is index iteration, and the other iterates over every element

1 Like

try playing with the range function. range(0,10,2), range(0,10), it’ll give you an idea of how you may use it in the future.

1 Like

so basically by doing
range(length(list))

We get the index values of everything in the list

But my question is how?
I can’t wrap my brain around the logic of it

it gives me a range of numbers

so im getting the range of the length of the list

which is basically indexing…
i get it!

2 Likes

Yes! It’s a very common and powerful tool in programming.

Once you have an index you can access anything in a list. Conversely, once you have the value, you can also access the indices where it appears on the list.

What should be underlined though is the strength of dividing the concepts and testing them out. This comes in handy when you get to more complicated topics.

1 Like

Thanks man, appreciate it