I want to pass a slice to a function so I can select a portion of a list. Passing as a string is preferable as I will read the required slice as a command line option from the user.
def select_portion(list_to_slice, slicer):
return(list_to_slice[slicer])
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
slicer = "1:4"
print(select_portion(numbers, slicer))
I get the following:
TypeError: list indices must be integers or slices, not str
which is understandable but I don't know how to modify this to get the intended output of:
[1, 2, 3]
You want the slice
constructor. In that case, that would be slice(1, 4, None)
(which corresponds to 1:4:
).
Just use slice
:
def select_portion(list_to_slice, slicer):
return(list_to_slice[slicer])
sl = slice(1, 4, None)
select_portion([1,2,3,4,5], sl)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With