Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I currently have a list and I want to update this list by removing any of the entries that meet a particular criteria.

So, for example I have the following:

    my_list = ['apple', 'pie', 'cat-video', 'dog.mp3']
    my_list = [x for x in my_list if not x.endswith('-video')]
    my_list = [x for x in my_list if not x.endswith('-.mp3')]

Is there an easier way to do this?

share|improve this question

closed as off-topic by Ethan Bierlein, JaDogg, 200_success May 30 at 9:08

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

1  
Why is this question being downvoted? It looks perfectly fine. –  wei2912 May 30 at 8:43

1 Answer 1

Another way to write the same thing is using filter:

my_list = ['apple', 'pie', 'cat-video', 'dog.mp3']
my_list = list(filter(lambda x: not x.endswith('-video'), my_list))
my_list = list(filter(lambda x: not x.endswith('-.mp3'), my_list))

Or if you want to perform both filters in one step:

my_list = list(filter(lambda x: not x.endswith('.mp3') and not x.endswith('-video'), my_list))

... but I don't think this is any easier than the simple list comprehension in your post. See also this related discussion. Also, PyLint doesn't seem to like filter. So you might really be better off with your original version.

And strictly speaking, your method and this one don't "update" a list, but replace it with another list.

share|improve this answer
    
Thanks, I was just curious if there was a more "elegant" way of doing so. Cheers! –  drincruz May 31 at 14:46

Not the answer you're looking for? Browse other questions tagged or ask your own question.