I have a problem in Python. I want to get the minimum index of a List:
for j in range(nbr_usines):
L.append(Dij[j][i])
indice_min=L.index(min(L))
In the terminal it is fine with L.index(min(L))
, but when I compile the program programa(Bij,Dij,Vi,Pi)
it tells me:
ValueError: min() arg is an empty sequence
The error occurs because you are applying
min()
to an empty list . You can reproduce it with:For some reason
L
it is an empty list, possibly, given what you show, it is because it is equal tonbr_usines
0). If this should not happen, check your code because you are generating the list wrong. Instead, if this possibility exists naturally in your program, then you should handle the exception. One solution would be to use a conditional that checks whether or not the list is empty:Or more compactly:
Or use
try-except
:If you also need the element itself in addition to its index, you have other possibilities:
Use a generator and
enumerate
:The same in one line:
Use
operator.itemgetter
together withenumerate
:or alternatively:
In all cases if the list is empty it is returned
None
, you can modify this as you like depending on what you use it for in your entire program.