I'm starting in the world of python and I'm trying to sort a list of objects under a certain criteria, but when I indicate the criteria I get the error
Expected collections.Iterable, got 'None' instead`.
I have a class Prenda
:
class Prenda():
def __init__(self,identificacion,descripcion,precio,stock,tipo):
self.identificacion = identificacion;
self.descripcion = descripcion;
self.precio = precio;
self.stock = stock;
self.tipo = tipo;
def toString(self):
print("Identificacion: " + str(self.identificacion))
print("Descripcion: "+self.descripcion)
print("Precio: $"+str(self.precio))
if stock > 0:
print("Cantidad en stock: " +str(self.stock))
else:
print("No queda stock")
print("Tipo de prenda: "+str(self.tipo))
I have a small code that requests the number of garments to load and with a cycle for
I request the data according to the number of garments that I enter:
for x in range(cantidad):
identificacion = int(input("Identificacion de prenda: "))
descripcion = input("Descripcion: ")
precio = float(input("Precio: "))
stock = int(input("Cantidad en stock: "))
tipo = int(input("Tipo de prenda (valores entre 0 y 14, con ambos numeros incluidos): "))
print()
p = Prenda(identificacion, descripcion, precio, stock, tipo)
lista.append(p)
while tipo < 0 or tipo > 14:
tipo = int(input("Tipo de prenda (valores entre 0 y 14, con ambos numeros incluidos: "))
p = Prenda(identificacion, descripcion, precio, stock, tipo)
lista.append(p)
print()
After this I try to show the data of all the garments from lowest to highest, according to their price, but this is where I get the error:
for x in lista.sort(key = x.precio): #<-- aca es donde me sale el error.
x.toString()
I have also tried with:
for x in lista.sort(key= lambda prenda: prenda.precio):
x.toString()
It doesn't work either, if I try to execute the code even with the error, when I reach the line where the is .sort()
, it throws me the following error.
Traceback (most recent call last):
File "C:/Users/Usuario/PycharmProjects/pythonProject/main.py", line 53, in <module>
for x in lista.sort(key= lambda prenda: prenda.precio):
TypeError: 'NoneType' object is not iterable
sort()
The list method does not return any value, what it does is rewrite the list in order.When you make an expression like this
The variable takes the values of the return of
l.sort()
, that isNone
This is clearly not valid. Because it is expected to
l.sort()
be an iterable. Instead consider sorting the list before iterating.You can also use the function
sorted
:In both examples
l
it is the list in question, andkey
the argument that defines the sort method.