Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

How do I create a new list only with words thta end with 'ant'?

+3 votes
asked Nov 6, 2021 by Lo Canu (250 points)

This is the list:

liste_ant = ["enfant", "bonjour", "éléphant", "aidant", "saumon", "amusant", "blessant", "piscine", "broyant", "carburant", "devant", "vibrant"]

3 Answers

+1 vote
answered Nov 7, 2021 by Peter Minarik (84,720 points)
edited Nov 7, 2021 by Peter Minarik

You need to know string slicing for this and how to append elements to a list.

With this knowledge, you can write a similar program:

liste_ant = ["enfant", "bonjour", "éléphant", "aidant", "saumon", "amusant", "blessant", "piscine", "broyant", "carburant", "devant", "vibrant"]
ants = []

for element in liste_ant:
    if element[-3:] == "ant": # slice string from the 3rd element from the right until the end, check if it equals to "ant"
        ants.append(element)  # append this element to the ants list

for ant in ants:
    print(ant)
+1 vote
answered Nov 7, 2021 by Dino Vity (740 points)

Using List Comprehension:

liste_ant = ["enfant""bonjour""éléphant""aidant""saumon""amusant""blessant""piscine""broyant""carburant""devant""vibrant"]

ends_with_ant = [ x for x in liste_ant if x[-3:] == "ant" ]

commented Nov 8, 2021 by Peter Minarik (84,720 points)
I prefer this to my own solution. I'm not a Python programmer, so it's good to learn things can be done in a more compact way. :)
0 votes
answered Feb 23, 2022 by Kokoz (340 points)
You also could check the built-in methods- startswith() and endswith()
They are very useful
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...