When you ask a question, don’t forget to include a link to the exercise or project you’re dealing with!
I’m stuck on #12. I don’t understand list comprehension. Can someone please explain them to me? It doesn’t make sense to me.
It can be confusing. It’s a quick(er), one line operation to create a new list, essentially.
Basic structure for list comprehensions:
[expression for item in list]
But this one adds a condition in the expression:
x for x in range(len(x) if blah is < blah
Check the docs:
“Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.”
So, step 12:
" Use a list comprehension to create a list called
cuts_under_30 that has the entry
hairstyles[i] for each
i for which
new_prices[i] is less than
30. You can use
range() in your list comprehension to make
i go from
len(new_prices) - 1"
The easiest way to explain is when you come upon stuff like this, break down the question into smaller bits.
1.) you create a variable called
2.) you’re comparing indexed items in three lists and adding a condition to produce a new list.
- The indexed item, in
hairstyles[i] for element [i] in the 2nd list (using range & len),
for [i] in range(len(prices))
- then you add your condition from the 3rd list: `if new_prices[i] <30]
cuts_under_30 = [hairstyles[i] for i in range(len(prices)) if new_prices[i] < 30]
['bouffant', 'pixie', 'crew', 'bowl']
The hint is helpful too:
“new_list = [old_list[i] for i in range(len(old_list)) if different_list[i] < 0]”
And, the forums have several threads on list comprehensions too.