Ethr
Ethr

Reputation: 461

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

Upvotes: 1

Views: 2315

Answers (3)

Mikhail Stepanov
Mikhail Stepanov

Reputation: 3790

It's not a python [slice][1], but causes a syntax error, because [..] syntax for getting a slice, not creating it:

slice = [2:5]
Out:
...
SyntaxError

slice is a python builtin, so don't shadow it's name. Create slice as

my_slice = slice(2, 5, 1)

where first argument is a start value, next is a stop value and the last is the step size:

my_list = list(range(10))
my_list
Out:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

my_list[my_slice]
Out:
[2, 3, 4]

my_list[slice(3, 8, 2)]
Out:
[2, 4, 6]

Note that we should use [] with a slice, as it calls a __getitem__ method of a list which accepts a slice objects (look last link for the __getitem__ and slice).

Upvotes: 0

Heyran.rs
Heyran.rs

Reputation: 513

Try this:

word = 'abc'*4
w = list(word)
s = slice(2,6,2)
print("".join(w[s]))

Upvotes: 0

mkrieger1
mkrieger1

Reputation: 23144

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'

Upvotes: 5

Related Questions