List comprehension vs loop - what do i not understand?

Viewed 62

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']

5 Answers

Try this:

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:
    loop_sales.append(sale.strip("$"))
print(loop_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

As a method, strip does not change the string itself, it just returns a stripped version of the string. So you can approach this in 2 ways. Either save the returned string as a variable and append that variable or append sales.strip($)

so like this: version 1 (saving as variable):

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:
    a= sale.strip("$")
    loop_sales.append(a)
print(loop_sales)

or version 2:

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:
    loop_sales.append(sale.strip("$"))
print(loop_sales)

This all depends on whether or not you will use the variable later on in the code but I think the second version is better if not.

strip doesn't change the string, it returns the stripped string.

enter image description here

loop_sales =[]
for sale in sales:
    loop_sales.append(sale.strip("$"))
print(loop_sales)
Related