Carleys Clippers - list comprehension

Hello, I’m doing the Carleys Clippers exercise (https://www.codecademy.com/courses/learn-python-3/projects/carlys-clippers)

I’ve used the hint to get it to work but I’m just after a little more information on why it does it this way…

Step 13 asks you to make a list of the hair cuts you can get for less than £30

The lists it gives you are:

hairstyles = ["bouffant", "pixie", "dreadlocks", "crew", "bowl", "bob", "mohawk", "flattop"]

prices = [30, 25, 40, 20, 20, 35, 50, 35]

It asks you to use list comprehension, I managed to figure it out based off of the hint:

new_list = [old_list[i] for i in range(len(old_list)) if different_list[i] < 0]

What I’m currious about is why it reccomends using

range(len(old_list))

Isn’t this just the same as

for i in old_list

Obviously it isn’t but I can’t figure out why

Cheers!

Sam :smiley:

without using range, how are we going to get the values from the prices list:

different_list[i] < 0

why is it called/name different list here? And the condition doesn’t seems right

of course, we could have used zip() instead

1 Like

Sorry, I didn’t know what your giving answers policy was :grimacing:

This is what I used

cuts_under_30 =[hairstyles[i] for i in range(len(hairstyles)) if prices[i] < 30]

I just ran

print(range(len(hairstyles)))

and it outputted

range(0, 8)

I’m assuming that mean it runs the loop from 0 to 8 but how is the different for just running for every value in a given list?

Sorry if it’s really obvious! (I’m not liking the lists part :weary:)

Given you have a question about the answer, I think its fine.

But that is my question for you, if you do:

for hairstyle in hairstyles

how are you going to get the values from the prices list?

by using range() (which gives us numbers we can use for indexes), we can use this index to get values from both lists.

of course, if we wanted to get values from both lists, python also has a built-in function for that. Which is zip().

Ahh right it makes sense now!

So without using range you can’t tell exactly which index location in the hairstyles/prices list your currently looking at?

So the i in this contect will be the current index location your looking at in hair styles?

exactly. And given we need something from the other list at the same index/position as well, using indexes is the way to go

yes, i has become a sort of unofficial abbreviation of index. Developers are so lazy on occasion.

2 Likes

Thank you so much!

I mean really the concept of having a variable in a loop isn’t that difficult to understand but from an ‘outsiders’ perspective when you see i there it really confuses things!