Get list names that are 4 in size

Asked

Viewed 50 times

1

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

I wrote the code below but apparently the loop is not working since, in a list with 4 names, being two 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

2 answers

4


You need to initialize the list outside the loop, the way you are doing each analyzed item 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. Go on to 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"]))

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Thank you very much, my friend.

3

For future references, you can solve in a row, with an equivalent code, using the so-called list comprehension:

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.