0

I am trying to slice a list on certain conditions and if the condition is False I want to return the full list by only changing the [x:y] values.

list = [0,1,2,3,4,5]

if condition == True:
    y = 3
    x = 0
else:
    y = I_dont_know
    x = I_dont_know
return list[x:y]

Below is the current method I am trying to use but as you can see it is removing the last item of the list

>>> list = [0,1,2,3,4,5]
>>> len(list)
6
>>> len(list[0:-1])
5
>>> list[0:-1]
[0, 1, 2, 3, 4]
>>>

how do I stop the last item from getting sliced off and/or is there a better method?

  • 1
    Unrelated, but it's probably best not to name your list `list`, because that's a builtin. – Dan Getz Sep 18 '22 at 13:41
  • 3
    "how do I stop the last item from getting sliced off" The (simplest) necessary value for the stopping point is `None` (or if you write the slice directly, you can just omit it). Please see the linked duplicate to understand why. Alternately, instead of trying to choose where to slice conditionally, you can just... conditionally either slice or not slice the list. – Karl Knechtel Sep 18 '22 at 13:42
  • 1
    Upper boundaries in slices are *exclusive*, so `my_list[0:-1]` means "everything except the last element". You can do `my_list`, `my_list[:]`, `my_list[0:]`, `my_list[0:len(my_list)]` or even `my_list[0:None]` as Karl Knechtel noted. – fsimonjetz Sep 18 '22 at 13:43
  • 1
    list[0:-1] here means the last iteration before -1. So, if you want to get all iteration use list[0:] – adwib Sep 18 '22 at 13:47

0 Answers0