Can I use a variable to slice my list in Python?

Question:

I am trying to write a code that takes the middle of the list and REMOVES the middle index element and the next index element from the list and put it in a new list.

def odd_indices(lst):
  x = len(lst)/2
  new_lst = lst[:x] + lst[x-1:]
  return new_lst
  
print(odd_indices([4, 3, 7, 10, 11, -2]))

(I am trying to remove "7" and "10" from the list)

In theory, the output should be

[4, 3, 11, -2]

but that is not the case as instead I get an error

    Traceback (most recent call last):
  File "script.py", line 9, in <module>
    print(odd_indices([4, 3, 7, 10, 11, -2]))
  File "script.py", line 5, in odd_indices
    new_lst = lst[:x] + lst[x-1:]
TypeError: slice indices must be integers or None or have an __index__ method

I believe that this error is caused due to me using a variable in a slice.

Please let me know what the fix to it is!

Asked By: shakeey

||

Answers:

You were close, but that’s not the issue. x is not an int here, it’s a float. Whenever you use /, the result will always be a float. You can use floor division to get around that. Instead of len(lst) / 2, use len(lst) // 2. Also, unrelated to your question, but change lst[x-1:] to lst[x+1:] to get the desired effect.

Answered By: Anonymous4045
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.