python - Print list elements that end with the letter 'a'

-1

Considering the following list:

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

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

Well, for a list of integers, you could do this:

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

I know I could do 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 do not think you're okay!

Any ideas, please?!

Thank you,

    
asked by anonymous 01.05.2018 / 12:54

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 run out of 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 to list only the names that end 'a' (using list understanding ):

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']
    
01.05.2018 / 13:14