18

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]
Sandy
  • 201
  • 2
  • 9

2 Answers2

12

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)
han solo
  • 6,390
  • 1
  • 15
  • 19
Netwave
  • 40,134
  • 6
  • 50
  • 93
  • This is nice but doesn't allow you to pass it in as a string? – Sandy Mar 21 '19 at 13:54
  • @Sandy You could do `>>> slice(*(int(x) for x in '1:4'.split(':')]))` `slice(1, 4, None)`. But i am not sure, if this is frowned upon. If you prefer `map` instead of `list` comprehension `>>> slice(*map(int, x.split(':')))` – han solo Mar 21 '19 at 13:57
  • @hansolo it's not a great idea... any arguments can be missed... for instance `::3`, `:3:-1` or even just `:` and `::` are valid. – Jon Clements Mar 21 '19 at 15:36
  • @JonClements Yes, i see the point – han solo Mar 21 '19 at 16:50
8

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

gmds
  • 19,325
  • 4
  • 32
  • 58