Slice indices must be integers or None or have __index__ method

PythonSlice

Python Problem Overview


I'm trying something with Python. I want to slice a list (plateau) in several list (L[i]) but I have the following error message:

  File "C:\Users\adescamp\Skycraper\skycraper.py", line 20, in <module>
    item = plateau[debut:fin]
TypeError: slice indices must be integers or None or have an __index__ method

The concerned line is the one with item = plateau[debut:fin]

from math import sqrt

plateau = [2, 3, 1, 4, 1, 4, 2, 3, 4, 1, 3, 2, 3, 2, 4, 1]

taille = sqrt(len(plateau))

# Division en lignes
L = []
i = 1
while i < taille:
    fin = i * taille
    debut = fin - taille
    item = plateau[debut:fin]
    L.append(item)
    i += 1

Python Solutions


Solution 1 - Python

Your debut and fin values are floating point values, not integers, because taille is a float.

Make those values integers instead:

item = plateau[int(debut):int(fin)]

Alternatively, make taille an integer:

taille = int(sqrt(len(plateau)))

Solution 2 - Python

When you slice a list the slices must be integers.

Take notice of the type of your indices variables or of possible operations you are performing while slicing

a = [1, 2, 3, 4]
b = a[:len(a)/2] # Will give your error because in python division ALWAYS returns float
c = a[:len(a)//2] # Correct answer

I know this isn't exactly a good response to your question in particular, but it's a broader answer.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDescampsAuView Question on Stackoverflow
Solution 1 - PythonMartijn PietersView Answer on Stackoverflow
Solution 2 - PythonLucas SousaView Answer on Stackoverflow