Len's Slice Help

Whats wrong with my .sort()?

My Code;
toppings = [“pepperoni”, “pineapple”, “cheese”, “sausage”, “olives”, “anchovies”, “mushrooms”]

prices = [2, 6, 1, 3, 2, 7, 2]

num_two_dollar_slices = prices.count(2)

print(num_two_dollar_slices)

num_pizzas = len(toppings)

print(“We sell " + str(toppings) + " different kinds of pizza!”)

pizza_and_prices = [ 2, “pepperoni”, 6, “pineapple”, 1, “cheese”, 3, “sausage”, 2,“olives”, 7, “anchovies”, 2, “mushrooms”]

print(pizza_and_prices)

pizza_and_prices.sort() <<<<<< error

cheapest_pizza = pizza_and_prices[0]

priciest_pizza = pizza_and_prices [-1]

pizza_and_prices.pop()

pizza_and_prices.insert[2.5, “peppers”]

three_cheapest = pizza_and_prices[:2]

print(three_cheapest)

Prints out this error:

Traceback (most recent call last):
File “script.py”, line 10, in
pizza_and_prices.sort()
TypeError: ‘<’ not supported between instances of ‘str’ and ‘int’

Exactly what the error says: “TypeError…”
You cannot use a comparison operator with a string and integer. The data that’s being compared has to be the same type.
Generally,:

results = "100" > 50
>>TypeError: '>' not supported between instances of 'str' and 'int'

#which is resolved by casting one of them as a string or int. 
#example:

results = int("100") > 50
print(results)
>>True

Also:
Check out some of these posts for a hint:
https://discuss.codecademy.com/search?q=Len%27s%20Slice%20sort

That said, there’s an error here:

  • print(“We sell " + str(toppings) + " different kinds of pizza!”)

Why are you casting a list of strings-- toppings-- as a string?
Shouldn’t you replace “toppings” with num_pizzas? (which you used the function len() on previously, which returns the number of items in the list.)

The list, pizza_and_prices has integers and strings…which is why one has to cast it as a string when using the print() b/c you’re concatenating it with other strings.
side note: Can’t you use .zip(prices, toppings) to create a combined list and then use print(list(pizza_and_prices))
OR, has .zip() not been introduced yet? (I forget).

More importantly,

  • .sort() returns nothing and makes changes to the original sequence. ie: it modifies the list in place and returns None. Note: " This method sorts the list in place, using only < comparisons between items."

  • .sorted() creates a new sequence type that contains the original sequence. It also takes/accepts any kind of iterable.

See the docs:

You could also use print(pizza_and_prices) to see what occurs.

Other things:

  • there’s an error here:
    pizza_and_prices.insert[2.5, “peppers”]
    (hint: you’re missing a parameter (what is the index where you would insert?) with .insert() See: 5. Data Structures — Python 3.11.2 documentation

  • There’s also an index error here:
    three_cheapest = pizza_and_prices[:2]

Sorry, that was longwinded. :upside_down_face:

2 Likes