I have a list below where I am trying to add a [2.5, "peppers"] in a specific place in the list using the .insert
method:
pizza_and_prices = [
[2, "pepperoni"],
[6, "pineapple"],
[1, "cheese"],
[3, "sausage"],
[2, "olives"],
[7, "anchovies"],
[2, "mushrooms"]
]
#sort pizza list
pizza_and_prices.sort()
#drawing from 2d list
cheapest_pizza = pizza_and_prices[0]
priciest_pizza = pizza_and_prices[-1]
#purchases
pizza_and_prices.pop()
pizza_and_prices[4].insert([2.5, "peppers"])
Since the .sort()
method by default sorts a 2D list by whatever is first in the sublist. the output should be:
[[1, 'cheese'], [2, 'mushrooms'], [2, 'olives'], [2, 'pepperoni'], [3, 'sausage'], [6, 'pineapple']]
Now say I am trying to add [2.5, "X"]
to my 2-Dimensional list called "pizza_and_prices"
(whilst keeping it in order of prices) using the .insert
method. How do I do that exactly?
CodePudding user response:
.Insert method
Syntax
list.insert(position,element)
You can loop over the list to figure out the index where to place the given element:
ind = 0
for i in pizza_and_prices:
if i[0] > 2.5:
break
else:
ind = 1
pizza_and_prices.insert(ind,[2.5,"y"])
CodePudding user response:
You have to give 2 arguments to the insert(arg1, arg2)
function. arg1
is an index where you want to add something, and arg2
is what you want to add at arg1
index. Keep in mind that the index of data stored at and beyond will be increased by 1.
The potential solution you are looking for is
pizza_and_prices = [
[2, "pepperoni"],
[6, "pineapple"],
[1, "cheese"],
[3, "sausage"],
[2, "olives"],
[7, "anchovies"],
[2, "mushrooms"]
]
#sort pizza list
pizza_and_prices.sort()
#drawing from 2d list
cheapest_pizza = pizza_and_prices[0]
priciest_pizza = pizza_and_prices[-1]
#count prices - task 3
num_two_dollar_slices = prices.count(2)
#purchases
pizza_and_prices.pop()
pizza_and_prices.insert(4, [2.5, "peppers"])