Little confusion in List Comprehension

From my knowledge that i learn from previous chapter of using list comprehension is like:

usernames = [word for word in words if word[0] == '@']

But i have some confusion, the way how they use list comprehension

cuts_under_30 =[hairstyles[x] for x in range(len(new_prices)) if new_prices[x] < 30]

someone please explain me, i know the objective is to return a list of hairstyles that are priced below 30$.

Here is exercise link:

that’s exactly the same format

Hello @thiyamsureshsingh, the two snippets provided do the same thing, in the same way. The only major difference is this:

This just identifies each element of the list hairstyles. The rest of the list comprehension works the same way.

Hi there.

Consider that you can refactor a list comprehension to use a for loop, and the list .append() method:

usernames = []

for word in words:
  if word[0] = "@"

cuts_under_30 = []

for x in range(len(new_prices)):
  if new_prices[x] < 30:

In both of these cases, the code above is doing the same job as your list comprehension. It’s just less concise. :slight_smile:

1 Like

Hmmm, this requires a bit of visualization.

hairstyles = [hS1, hS2, hS3, hS4, hS4]

hair_style_prices = [20, 40, 60, 25, 80]

The idea is that the idx of the hair_style_prices list is same index of the hair style with that price. So if we line them up to get

[hS1]-[hS2]-[hS3]-[hS4]-[hS4] = hairstyles
0-------1-----2-----3-----4 = indexs
[20]—[40]—[60]—[25]—[80] = new_prices

Lets use an expanded for loop:

for idx in range(len(new_prices)):

if new_prices[idx] < 30:


So, you simply say, if the hairstyle is in the same column (with respect the the example.1) as the price, and if the price is less then 30, then we add the hairstyle to our list.

I hope this helped. :slight_smile: