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']
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With