Search code examples
pythonsliceunpack

Is it possible to unpack values from list to slice?


I'm trying to use values in list to select part of word. Here is working solution:

word = 'abc'*4
slice = [2,5]  #it can contain 1-3 elements

def try_catch(list, index):
    try:
        return list[index]
    except IndexError:
        return None

print(word[slice[0]:try_catch(slice,1):try_catch(slice,2)])

but I wonder if is it possible to shorten it? Something like this comes to my mind:

word = 'abc'*4
slice = [2,6,2]
print(word[':'.join([str(x) for x in slice])]) #missing : for one element in list

It produces:

TypeError: string indices must be integers

Solution

  • You can use the built-in slice (and need to name your list differently to be able to access the built-in):

    >>> word = 'abcdefghijk'
    >>> theslice = [2, 10, 3]
    >>> word[slice(*theslice)]
    'cfi'