-1

it is possible to use string for slice the list?

i have example like this

m = [1,2,3,4,5]
print(m[:-1])
print(m[1:-1:])
print(m[::2])

above code will result

[1, 2, 3, 4]
[2, 3, 4]
[1, 3, 5]

so i want use string to do something like that

m = [1,2,3,4,5]
inp = input('slice the list ')

#and user will input [:-1], [1:-1:], or [::2]

#slice the list using that input
#m[inp]??

if this possible, how to make this approach?

i cannot find answer for this anywhere or i just don't know what keyword should i type for search this

alnyz
  • 91
  • 1
  • 1
  • 9
  • 2
    Outside of a few very specific situations, user input shouldn't be code, or have any connection to the language you're writing your program in. There are a few reasons: it's awkward UI design, it introduces massive security problems, and it makes reimplementing things in a different language much more difficult than it needs to be. – user2357112 Feb 28 '23 at 15:54
  • An answer provided suggests using *eval()*. That will work under controlled situations but is generally considered bad form. You could write a fairly trivial parser and then construct a *slice* class. But, as @user2357112 rightly implies - this is rather bizarre and potentially unmanageable – DarkKnight Feb 28 '23 at 15:59

1 Answers1

0

You can build a slice object and use that as an arg to the [] operator (or equivalent __getitem__ magic method). slice takes optional int arguments (or None to use the defaults) that correspond to the numbers in the -1:1: syntax.

So if you want to parse a string like [1:-1:] without directly using eval (which can be dangerous since it will also parse all sorts of other expressions), you can do something along the lines of:

  • strip the [] characters
  • split on :
  • pass the :-separated numbers as args to slice(), using None for missing numbers.

E.g.:

>>> inp = "[1:-1:]"
>>> inp_slice = slice(*(int(i) if i else None for i in inp.strip("[]").split(":")))
>>> [1,2,3,4,5][inp_slice]
[2, 3, 4]

Once you understand how the slice object works, you're of course free to accept the input from the user in other forms (e.g. there's no reason to require them to input the [] part if you know that the input is always going to be used to slice a list).

Samwise
  • 68,105
  • 3
  • 30
  • 44