Search code examples
pythoncoding-style

What is the most pythonic way to exclude elements of a list that start with a specific character?


I have a list of strings. I want to get a new list that excludes elements starting with '#' while preserving the order. What is the most pythonic way to this? (preferably not using a loop?)


Solution

  • [x for x in my_list if not x.startswith('#')]
    

    That's the most pythonic way of doing it. Any way of doing this will end up using a loop in either Python or C.