I have a list that looks like this:
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
I'd like to generate a filtered list that looks like this:
filtered_lst = [2, 6, 7, 9, 10, 13]
Does Python provide a convention for custom slicing. Something such as:
lst[1, 5, 6, 8, 9, 12] # slice a list by index
I'd go with the
operator.itemgetter()
method that Martijn Pieters has suggested, but here's another way (for completeness)Use
operator.itemgetter()
:Demo:
This returns a tuple; cast to a list with
list(itemgetter(...)(lst))
if a that is a requirement.Note that this is the equivalent of a slice expression (
lst[start:stop]
) with a set of indices instead of a range; it can not be used as a left-hand-side slice assignment (lst[start:stop] = some_iterable
).It's easily and straightforwardly done using a list comprehension.
A Python slice allows you to make the slice the target of an assignment. And the Python slicing syntax does not allow for slices with irregular patterns of indices. So, if you want to make your "custom" slice the target of an assignment, that's not possible with Python slice syntax.
If your requirements are met by taking a copy of the specified elements, then
operator.itemgetter()
meets your needs. If you need slice assignment, then numpy slices are a good option.Numpy arrays have this kind of slicing syntax: