Trouble expressing a list comprehension as a for loop

Hi there,

In the Carly’s Clipper exercise:
carlys clippers

I understand how to complete task 13 using a comprehensive list below

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

However in order to make sure I understood for loops, I tried to do the same thing with the below code:

for i in range(len(hairstyles)):
__ if new_prices[i] < 30:
__ _cuts_under_30 += hairstyles[i]

I was frustrated that when I printed cuts_under_30 the out put was:

[‘b’, ‘o’, ‘u’, ‘f’, ‘f’, ‘a’, ‘n’, ‘t’, ‘p’, ‘i’, ‘x’, ‘i’, ‘e’, ‘c’, ‘r’, ‘e’, ‘w’, ‘b’, ‘o’, ‘w’, ‘l’]

Can someone please explain what I am doing wrong?

Hi,

You have the gift of understanding list comprehensions first, it’s usually the other way around :slight_smile:

Format:
[item for item in some_list]
will go through every item in a list and return a new copy of the list (at minimum, but you can make it do other things obviously).

to do the same in a for-loop you’d do the following

copy = []
for item in some_list:
    copy.append(item)
    #note, here every item is being cycled and you can operate on it here

Note how each return happens explicitly in the for-loop (instead of the end-product bundled in a list).

Code examples in a terminal (you’d need print(item) to replicate this in a script):

>>> lst = [1,2,3]
>>> test = [item for item in lst]
>>> test
[1, 2, 3]
>>> lst==test
True
>>> id(lst)
140672309925200
>>> id(test)
140672310823824
# the 6 lines above highlight that lst and test not the "same" 
# object, but contain the same value
>>> for item in lst:
...     item
1
2
3
>>> copy = []
>>> for item in lst:
...     copy.append(item)
>>> copy
[1, 2, 3]

In general for-loops are more flexible and list-comprehensions are more concise. List-comprehensions tend to have slightly better performance as well. Readability will depend on context, sometimes one is more readable than the other. Any nesting is usually left to the domain of for-loops (or perhaps some recursive pattern).

2 Likes

Understood. Thank you so much for your help!

1 Like