Get names from a list that have a size equal to 4

1

I am trying to solve the following problem: from a list of names, I need to return only names with len 4.

I wrote the code below but apparently loop is not working since in a list with 4 names, two being within the criteria, it only returns one.

def nomes(x):
    for i in x:
        y = len(i)
        nome = []
        if y == 4:
            nome.append(i)
    return nome
    
asked by anonymous 13.07.2018 / 03:51

2 answers

3

You need to initialize the list outside the loop, the way you are doing each item you are analyzing is starting the list from scratch and you lose what you have already done. Whenever you encounter a problem, analyze what the code is doing. It will explain what it does line by line, do a table test .

def nomes(x):
    nome = []
    for i in x:
        if len(i) == 4:
            nome.append(i)
    return nome

print(nomes(["abc", "jose", "ana", "maria", "joao", "abcd"]))

See running on ideone . And on Coding Ground . Also I put GitHub for future reference .

    
13.07.2018 / 03:59
2

For future reference, you can solve on a line, with an equivalent code, using the so-called list understanding:

def nomes(lista, tamanho):
    return [nome for nome in lista if len(nome) == tamanho]

The function receives the list of names and the desired size, which in this case would be 4; scrolls through all the names in the list, and if the size matches the size you want, add it to the output list.

    
13.07.2018 / 04:34