Python - print list elements that have 5 letters

Asked

Viewed 402 times

0

Boas, Having the following list::

lista_nomes =['Manuel', 'Laura', 'Antonio', 'Jasmim', 'Maria','Silvia', 'Lu', 'Pancrácio', 'Diogo', 'Ricardo', 'Miguel', 'Andre',]

I want to print the list elements that have 5 letters.

Turns out I’m not getting it.

lista_nomes =['Manuel', 'Laura', 'Antonio', 'Jasmim', 'Maria',
'Silvia', 'Lu', 'Pancrácio', 'Diogo', 'Ricardo', 'Miguel', 'Andre',]


for elem in lista_nomes:
   if elem == 5:
       lista_valida.append(elem) 
print (elem)
  • 1

    What you want is to check if the string (name) has 5 characters, not if nome == 5, This we know will not be. Use len() to see the length (how many characters) of the string

  • 1

    'Cause...I thought it would work out that way.!

  • 1

    And I think you also have to declare lista_valida = [] before the for

  • Yes, I do! My mistake of not doing it!

1 answer

4


You can use the function len()

lista_nomes =['Manuel', 'Laura', 'Antonio', 'Jasmim', 'Maria', 'Silvia', 'Lu', 'Pancrácio', 'Diogo', 'Ricardo', 'Miguel', 'Andre',]
nomes = [nome for nome in lista_nomes if len(nome) == 5]
print(nomes)

Behold running on repl.it

Browser other questions tagged

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