user4444
user4444

Reputation: 45

How to multiply every 2 element of each list in my 2d list by a variable

I have made a 2d list with lists of 3 elements in each list. I am trying to multiply the second element of every list in the 2d list by a variable I have previously set. 'total_recipe' is the 2d list. 'scale_factor' is the variable I am trying to multiply with.

I have tried to change the value of the second element by using this code below after research. But I am getting an error message. I do not understand how to change the value of an element of the list if the elements in the list are inputted.

(I have set what the elements could be in the list below. However the 2d list is inputted by the user, so the values of the elements and number of lists inside the 2d list could change)

Here is my code:

scale_factor = 6   
total_recipe = [['flour', 6.0, 4], ['tiger', 4.0, 3], ['apple', 6.0, 3]]

for i in range(len(total_recipe)):
    change_element = list(total_recipe[0])
    change_element[1] = (total_recipe[i][1]) * scale_factor
    print(total_recipe)

Upvotes: 0

Views: 99

Answers (3)

Abdulrahman Mohammed
Abdulrahman Mohammed

Reputation: 15

You can do it like this:

scale_factor = 6   
total_recipe = [['flour', 6.0, 4], ['tiger', 4.0, 3], ['apple', 6.0, 3]]

for i in range(len(total_recipe)):
    total_recipe[i][1] = total_recipe[i][1] * scale_factor
print(total_recipe)

You can iterate through the elements of the list total_recipe and multiply the second value element of each element (which is a list itself) by the scale factor

Upvotes: 0

Red
Red

Reputation: 27567

You can use this list comprehension:

scale_factor = 6   
total_recipe = [['flour', 6.0, 4], ['tiger', 4.0, 3], ['apple', 6.0, 3]]

scaled_recipe = [[l[0],l[1]*scale_factor,l[2]] for l in total_recipe]

print(scaled_recipe)

Output:

[['flour', 36.0, 4], ['tiger', 24.0, 3], ['apple', 36.0, 3]]

Upvotes: 0

Mark
Mark

Reputation: 92440

To multiply the second element just loop through and multiply. Python discourages you from using indices in loops. Just loop over the elements (not index in range) and it's simply:

scale_factor = 6   
total_recipe = [['flour', 6.0, 4], ['tiger', 4.0, 3], ['apple', 6.0, 3]]

for item in total_recipe:
    item[1] *= scale_factor

print(total_recipe)
# [['flour', 36.0, 4], ['tiger', 24.0, 3], ['apple', 36.0, 3]]

Upvotes: 3

Related Questions