Python Forum

Full Version: Filter out all words that begin with P, B, or T.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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 #?
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
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']
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']