Python Forum
Filter out all words that begin with P, B, or T.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Filter out all words that begin with P, B, or T.
#1
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 #?
Reply
#2
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
Reply
#3
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']
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#4
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']
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  how to write a code for term that can't begin or end with a stopword desul 3 3,776 Mar-18-2017, 03:42 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020