Home > Net >  multiplying lists with an external float in for loop
multiplying lists with an external float in for loop

Time:05-28

I have a list comprising wages for workers I want to give them a 50% raise so i want to multiply the list by 1.5 This is my code:

wages = [100, 150, 180, 250, 400]
for i in range(0,5):
    print("Previous wage for ", i, "was: ", wages[i])
    wages = [i * 1.5 for i in wages]
    print("New wage for ", i, "is", wages[i])

However this is the result i get:

Previous wage for  0 was:  100
New wage for  0 is 150.0
Previous wage for  1 was:  225.0
New wage for  1 is 337.5
Previous wage for  2 was:  405.0
New wage for  2 is 607.5
Previous wage for  3 was:  843.75
New wage for  3 is 1265.625
Previous wage for  4 was:  2025.0
New wage for  4 is 3037.5

The first wage is correct but then it starts giving results i do not want. Like wage for index[1] should be 150 previous and 225 new....etc

where am i getting it wrong please assist

CodePudding user response:

You are multiplying the entire list by a factor of 1.5 in every iteration of the loop. You can either, change it to only multiply the item at the index you are iterating.

wages = [100, 150, 180, 250, 400]
for i in range(len(wages)):
    print("Previous wage for ", i, "was: ", wages[i])
    wages[i] *= 1.5
    print("New wage for ", i, "is", wages[i])

Or using the list comprehension once.

wages = [100, 150, 180, 250, 400]
new_wages = [wage * 1.5 for wage in wages]
for i in range(len(wages)):
    print("Previous wage for ", i, "was: ", wages[i])
    print("New wage for ", i, "is", new_wages[i])

The statement with list comprehension multiplies all items in the wages list by 1.5, and assigns it to new_wages. new_wages is [150.0, 225.0, 270.0, 375.0, 600.0] after the assignment.

Edit: As per a comment by @Mad Physicist, you should avoid hardcoding numbers into your code. So instead of having 5 in your range function, use len() so it works after you add or remove numbers from the list.

  • Related