python - Print the list elements ending with the letter 'a'

Asked

Viewed 294 times

-1

Considering the following list:

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

What I want is to print out the elements of the list that end with the letter ' a'.

Well, for a list of integers, I could do like this:

>>> L = [1, 1, 2, 3, 5, 8, 13, 21]
>>> L[-1]
21

I know I could do it like this:

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


print(lista_nomes[1:2])
print(lista_nomes[5:6])
print(lista_nomes[4:5])

But I don’t think it’s okay!

Any ideas, please?!

Thank you,

1 answer

3


The logic to 'grab' the last element of each name (last letter) is the same (nome[-1]). Since a string in many languages is also an iterable, and python does not escape the rule:

To print all names whose last character is "a":

lista_nomes = ['Manuel', 'Laura', 'Antonio', 'Jasmim', 'Maria', 'Silvia', 'Lu', 'Pancrácio', 'Diogo', 'Ricardo', 'Miguel', 'Andre',]
for nome in lista_nomes:
  if(nome[-1] == 'a'): # verificar se ultimo caracter e um 'a'
    print(nome)
# Laura, Maria, Silvia

DEMONSTRATION

If you want a list only with names ending 'a' (using list comprehension):

lista_nomes = ['Manuel', 'Laura', 'Antonio', 'Jasmim', 'Maria', 'Silvia', 'Lu', 'Pancrácio', 'Diogo', 'Ricardo', 'Miguel', 'Andre']
nomes_a = [nome for nome in lista_nomes if nome[-1] == 'a'] # ['Laura', 'Maria', 'Silvia']
  • That’s what I wanted!!! Thank you very much!!! Excellent!

  • @Joaopeixotofernandes, you can do the same of my last example in for: https://repl.it/repls/PrimeMilkyBot

  • Yeah, I know. That’s just it!! :)

  • Like you said, "What I want to do is print...", which is why I made the first example with print. Next time say you want a list (;

  • what I meant was even with the for ! Thank you.

Browser other questions tagged

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