Find smallest string from a list in python


how do i make a function to determine the smallest string in a list ignoring spaces?

For example, when typing:

menor_elemento(["joão", "   a ", "arrozz"])

the output should return "a" (no spaces) as it is the shortest string (ignoring spaces).

Here is the code I tried:

def menor_nome(nome):
    m = min(nome)
    m = m.strip
    return m


Edited (New version):
In fact my original version is totally wrong, I didn't pay attention to the fact that what the question asks for is the smallest "size" of the string and not the smallest value. As I also noticed that the other answer was also not entirely correct, since it did not take into account the decode of the strings and not even when there are more than two strings with the same size as the minimum, I decided to make a new version.

Obs. Obviously I considered that the list always has the same data type, in the case of strings, because it would not make sense to mix strings and numerics in this context. For numeric it would be very easy to adapt the code, here it goes:


import unicodedata as ud

def min_list(_list_str):
    # Tamanho da lista
    len_list = len(_list_str)

    # Normalizando a lista (suprimindo acentos)
    list_str =  [  (ud.normalize('NFKD', s ).encode('ASCII','ignore').decode()).strip() for s in  _list_str]

    # Produz uma lista com os tamanhos de cada elemento
    lens = [len(s) for s in list_str]

    # Tamanho do menor (ou menores, quando empate) elemento
    min_len = min(lens)

    # Lista para guardar as strings cujos tamanhos sejam iguais ao minimo
    mins = []

    for i in range(len_list):
        # String normalizada
        s = list_str[i]
        if len(s)==min_len:
            mins.append(_list_str[i].strip() )

    return mins  

list_str = ['maria', 'josé', 'PAULO', 'Catarina]', ' kate  ', 'joão', 'mara' ]

print ( min_list(list_str) )
['josé', 'kate', 'joão', 'mara']

See the working code here.

Original version

min(["joão", "   a ", "arrozz"]).strip()


Scroll to Top