How to insert a float into a sorted list?

My first post to this forum. Total coding newbie here. Thanks in advance for your help. Stuck on a Python 3 tutorial project. I am stuck on question #12 of the link below

I need to insert [2.5, “peppers”] into the already sorted list, see below (variable name is pizza_and_prices)
[[1, ‘cheese’], [2, ‘mushrooms’], [2, ‘olives’], [2, ‘pepperoni’], [3, ‘sausage’], [6, ‘pineapple’], [7, ‘anchovies’]]

The first incorrect code I came up with, see below, produced a “TypeError: integer argument expected, got float” …
pizza_and_prices.insert(2.5, “peppers”)

The second incorrect code I came up with …
pizza_and_prices.insert(int(2.5), “peppers”)
produced the list below that has the price, 2.5, missing …
[[1, ‘cheese’], [2, ‘mushrooms’], ‘peppers’, [2, ‘olives’], [2, ‘pepperoni’], [3, ‘sausage’], [6, ‘pineapple’]]

Help please?

The .insert() method requires a position argument for where to insert. We see that the price, 3 is in the index[4] position so that would be the index to supply.

Note that we do not wish to convert this to an integer, but leave it as a float.

1 Like

Thank you mtf for writing back! I am still confused as to how I can insert a 2D list [2.5, “peppers”] into the existing and already sorted 2D variable list pizza_and_prices. Where in the code do I specify the index[4] position?

I need to go from this …
[[1, ‘cheese’], [2, ‘mushrooms’], [2, ‘olives’], [2, ‘pepperoni’], [3, ‘sausage’], [6, ‘pineapple’]]

to this …
[[1, ‘cheese’], [2, ‘mushrooms’], [2, ‘olives’], [2, ‘pepperoni’], [2.5, 'peppers], [3, ‘sausage’], [6, ‘pineapple’]]

1 Like

Here is an example,

pizza_and_prices.insert(4, [2.5, "peppers"])
#                       ^
#                       |
# the instruction is to insert before index[4]
1 Like

It worked! Thank you so much mtf! I was going cross-eyed trying to figure this out. Somehow I missed when this was taught in the tutorial…about how to insert a 2D list into a 2D variable list at a specific index. I don’t even know if I am using the write coding vocabulary to try to describe this … but you totally answered my question. Thank you again!

1 Like

float_sort is a fast templated in-place hybrid radix/comparison algorithm much like integer_sort , but sorts IEEE floating-point numbers (positive, zero, NaN, and negative) into ascending order by casting them to integers.