Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slice indices must be integers or None or have __index__ method

Tags:

python

slice

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 
like image 889
DescampsAu Avatar asked Dec 22 '13 19:12

DescampsAu


People also ask

How list indices must be integers or slices not str?

The Python "TypeError: list indices must be integers or slices, not str" occurs when we use a string instead of an integer to access a list at a specific index. To solve the error, use the int() class to convert the string to an integer, e.g. my_list[int(my_str)] . Here is an example of how the error occurs.

What does list indices must be integers or slices not list mean?

The Python "TypeError: list indices must be integers or slices, not float" occurs when we use a floating-point number to access a list at a specific index. To solve the error, convert the float to an integer, e.g. my_list[int(my_float)] .

How do you slice in Python?

Python slice() FunctionThe slice() function returns a slice object. A slice object is used to specify how to slice a sequence. You can specify where to start the slicing, and where to end. You can also specify the step, which allows you to e.g. slice only every other item.

What index is the default end index if it isn't specified in a slice?

The start parameter represents the starting index, end is the ending index, and step is the number of items that are "stepped" over. If step isn't explicitly given, the default value is 1 .


1 Answers

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))) 
like image 112
Martijn Pieters Avatar answered Sep 27 '22 21:09

Martijn Pieters