Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehension vs loop - what do i not understand?

I'm a little confused why my list comprehension is working, but not my for-loop.

Can someone explain what I'm missing here?

sales = ['$1.21', '$7.29', '$12.52', '$5.13', '$20.39', '$30.82', '$1.85', '$17.98']
# When for-loop
loop_sales =[]
for sale in sales:
    sale.strip("$")
    loop_sales.append(sale)
print(loop_sales)

Output: ['$1.21', '$7.29', '$12.52', '$5.13', '$20.39', '$30.82', '$1.85', '$17.98']


# When list comprehension
list_sales = [sale.strip("$") for sale in sales]
print(list_sales)

Output: ['1.21', '7.29', '12.52', '5.13', '20.39', '30.82', '1.85', '17.98']

like image 851
georgbhm Avatar asked Dec 10 '25 04:12

georgbhm


1 Answers

strip method just returns a new value (which is the processed output actually), It does not change the sale variable here at all. In order to make it work, try sale = sale.strip("$") instead of sale.strip("$") in your normal for loop code or just use loop_sales.append(sale.strip('$')) as Talha Tayyab said in his answer

like image 86
Ghost Ops Avatar answered Dec 11 '25 17:12

Ghost Ops



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!