Python Forum
Filter out all words that begin with P, B, or T. - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Filter out all words that begin with P, B, or T. (/thread-18097.html)



Filter out all words that begin with P, B, or T. - johneven - May-05-2019

Need help with the following:

Filter out all words that begin with P, B, or T.

colors = ["Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet", "Purple", "Pink", "Brown", "Teal", "Turquois", "Peach", "Beige"]
#my response below-
for position in range(len(colors)):
    color = colors[position]
    print(color)
    if color[0] in ["P", "B", "T"]:
        del colors[position]
print(colors)
Output:
Red Orange Yellow Green Blue #? Violet Purple #? Brown #? Turquois #? Beige #?



RE: Filter out all words that begin with P, B, or T. - Yoriz - May-05-2019

The position indexes are based on a full list, as soon as something is deleted from the list those indexes no longer relate to the correct position and there will be a IndexError: list index out of range because the list will no longer be big enough.
Rather then trying to alter the original list you should make a new list and only add the non filtered items to it.
After this is complete the original list variable can be assigned to the new list


RE: Filter out all words that begin with P, B, or T. - perfringo - May-06-2019

You can combine string method .startswith and list comprehension with conditional to get desired result. This one of the most straightforward translations of spoken language into Python: "give me color for every color in colors which is not starting with letters 'P', 'B', 'T'":

>>> [color for color in colors if not color.startswith(('P', 'B', 'T'))]
['Red', 'Orange', 'Yellow', 'Green', 'Indigo', 'Violet']



RE: Filter out all words that begin with P, B, or T. - michalmonday - May-07-2019

Alternatively:

import re
colors = ["Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet", "Purple", "Pink", "Brown", "Teal", "Turquois", "Peach", "Beige"]
filtered_colors = list(filter(re.compile('[^PBT]').match, colors))
print(filtered_colors)
Output:
['Red', 'Orange', 'Yellow', 'Green', 'Indigo', 'Violet']