Thursday, August 18, 2022

[FIXED] Why does output the for loop in Python the list for three times?

Issue

I am a beginner in Python. I am doing an exercise in which I must apply a discount to the items in the list prices and store the results in the list new_prices. Why is the output repeated three times? Is there a way to avoid it and get the output just one time?

Thank you in advance


prices = [2, 50, 70, 30]
new_prices =[]



for i in prices:
    prices[0] = 2 * 0.8
    prices[1] = 50 * 0.6
    prices[2] = 70 * 0.4
    prices[3] = 30 * 0.6
    new_prices.append(prices)


print(new_prices)


output: [[1.6, 30.0, 28.0, 18.0], [1.6, 30.0, 28.0, 18.0], [1.6, 30.0, 28.0, 18.0], [1.6, 30.0, 28.0, 18.0]]

expected output: [[1.6, 30.0, 28.0, 18.0]


Solution

The specific reason for the problem is that your for loop is unnecessary, but it rather looks like what you are really trying to do is something like this, where you have a number of different scale factors to multiply by the different elements of prices.

prices = [2, 50, 70, 30]

scale_factors = [0.8, 0.6, 0.4, 0.6]

new_prices = []
for price, scale_factor in zip(prices, scale_factors):
    new_prices.append(price * scale_factor)

print(new_prices)

Note the use of zip to take pairs of elements from prices and scale_factors.

You can also write this as:

new_prices = [price * scale_factor     
              for price, scale_factor in zip(prices, scale_factors)]


Answered By - alani
Answer Checked By - Candace Johnson (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.