Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python pass slice as argument [duplicate]

Tags:

python

slice

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]
like image 535
Sandy Avatar asked Mar 21 '19 13:03

Sandy


Video Answer


2 Answers

You want the slice constructor. In that case, that would be slice(1, 4, None) (which corresponds to 1:4:).

like image 186
gmds Avatar answered Oct 27 '22 17:10

gmds


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)
like image 21
Netwave Avatar answered Oct 27 '22 19:10

Netwave