Choose the appropriate data structure
You created a list of tuples, but if the idea is to map each product with its respective price, a dictionary seems more appropriate.
Not only does it make more sense for this case, it will also make the solution much easier. It would look like this:
lista_de_compras = {}
for produto in ['batata', 'cenoura', 'vagem']:
lista_de_compras[produto] = float(input(f'preço de {produto}, R$ '))
mais_barato = min(lista_de_compras, key=lista_de_compras.get)
print(f'Você deve levar {mais_barato} que custa R${lista_de_compras[mais_barato]:.2f}')
To print the price, I used the formatting options, to print always to two decimal places.
When using min
, i state that I want to use lista_de_compras.get
, what makes the prices are compared instead of the names. The result is the product that has the lowest price, and then just print it.
It just doesn’t solve tie cases, when more than one product is cheaper. In that case, just go through the dictionary and print everyone that has the same price:
mais_barato = min(lista_de_compras, key=lista_de_compras.get)
menor_preco = lista_de_compras[mais_barato]
print(f'produtos mais baratos, custam R${menor_preco:.2f}')
for produto, preco in lista_de_compras.items():
if preco == menor_preco:
print(produto)
Unless you already receive the list of tuples that way, there is no reason to use it, as a dictionary makes much more sense for this case. A another answer even shows that it can be solved with the list, but it becomes unnecessarily more complicated, and all because it is not the most appropriate data structure to solve the problem.
Choose the appropriate data structure is halfway towards a better code.