Amit Amit - 10 months ago 61
Python Question

Filter a List in Python With List Elements

I have a following list

list = ['Bucket1', 'ranbuck0', 'ranbuck1', 'ranbuck2', 'ranbuck3', 'ranbuck4', 'ranbuck5', 'ranbuck6', 'ranbuck7', 'ranbuck8', 'ranbuck9']

Is there a way to filter this list and create a new list, where I have the elements named with "ranbuck". I am not able to figure out the way how to iterate ranbuck1, ranbuck2 a append these in a list.

Thanks in Advance


You could use the list comprehension syntax of Python:

new_list = [_ for _ in list if 'ranbuck' in _]

Instead of the _s you could also introduce your own variable name for the temporary variable inside the list comprehension. Instead of 'ranbuck' in _ you could also write down another condition whether this element of the list should be in the new one or not.