Меню

Slice indices must be integers or none or have an index method ошибка

What is TypeError: slice indices must be integers or None or have an __index__ method?

If you have worked with lists/string in Python, you might have used the slicing technique for selecting specific elements. Using the : operator, you mention the starting index and ending index, between which are your required elements.

If the slicing is not done properly, you are bound to encounter the TypeError: slice indices must be integers or None or have an __index__ method error.

The solution to this problem is to use integers while mentioning slicing indices. Let us get into the details.

Example Using list

#Example of slicing indices type error
MyList = [12,45,13,34,23]
print(MyList)  #This will print the whole list
print(MyList[0:2] #This will print  [12,45,13]
print(MyList[0:'2']) #This will generate the TypeError

The above code will generate the following error.

TypeError: slice indices must be integers or None or have an __index__ method.

Here, line 4 of the code I.e print(MyList[0:’2’]) will throw an error because the ending index value is a string type and not integer.

TypeError slice indices must be integers or none or have an __index__ method

Example Using string

str = "Hello my name is XYZ"
print(str[0:5])   #This will print "Hello"
print(str[0:'5']) #This will Generate an error

Line 3 of the  i.e print(str[0:’5′]) above code will generate a TypeError :

slice indices must be integers or None or have an __index__ method error.

This is because the ending index value of the [ ] operator is a string and not integer. And we know, slice operator throws a TypeError when we provide value other than an integer to it.

Lists are indexed using whole numbers. Whole numbers are known integers. If you try to slice a list using a value that is not an integer, you’ll encounter the “TypeError: slice indices must be integers or None or have an __index__ method” error.

In this guide, we discuss what this error means and why it is raised. We’ll explore an example of this error in action so you can learn how to fix it in your program.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

TypeError: slice indices must be integers or None or have an __index__ method

Indexing lets you uniquely identify all the items in a list. Consider the following example:

Each item in our list has its own index number. We can use these index numbers to retrieve an individual item in a list, or a range of items in a list.

Index numbers increment by one for each value on a list. All the index numbers assigned to a list are stored as an integer.

You cannot access items from a list using a floating-point number. Although floating-points are still numbers, they are treated differently to integers. A floating point value does not correspond to any index number in a list.

An Example Scenario

We’re going to write a program that lets a teacher calculate how many times a student has earned a grade of over 75 in their class. We will give the teacher the option to restrict how many grades are searched.

To start, define a list of grades for a student:

grades = [73, 72, 90, 69, 83]

This list contains five values. We are going to ask the teacher how many grades the program should take into consideration. The grades are ordered by the time on which a test was taken. The last grade in the list is the most recent.

Let’s ask the user how many grades they want to review:

to_review = float(input(“How many grades would you like to take into consideration? ”))

We convert the value the user inserts to a floating-point number. This is because we need a number to access values from a list using their index numbers.

Next, use slicing to retrieve those items from our list:

list_of_grades_to_consider = grades[-to_review:]

This code retrieves the last X values from a list, where X is equal to the value that the teacher inserts into the program. For instance, this code retrieves the last two grades from the grades list if a teacher inserts 2 into the input field that we defined earlier.

Next, let’s write a for loop that calculates how many of these grades are over 75:

high_grades = 0

for g in list_of_grades_to_consider:
	if g > 75:
		high_grades += 1

We have defined a variable called high_grades which tracks how many times a student has earned a grade of over 75. We use a for loop to iterate over every grade in our list of grades to consider. If a grade is over 75, we add 1 to the high_grades value.

Finally, print out a message to the console that tells us how many times a student has earned a grade of over 75:

print(“This student has earned a grade of over 75 {} times.”.format(high_grades))

Let’s run our program and see what happens:

How many grades would you like to take into consideration? 3
Traceback (most recent call last):
  File "main.py", line 5, in <module>
	list_of_grades_to_consider = grades[-to_review:]
TypeError: slice indices must be integers or None or have an __index__ method

Our code asks our user how many grades they would like the program to consider. Then, our program stops and returns an error.

The Solution

We surrounded our input() statement with the float() method. This converts the value that the teacher inserts into our program to a floating-point number.

Our program returns an error because we’re trying to slice a list using a floating-point number. This is not possible because lists are indexed using integers.

To solve this problem, we’re going to use the int() method to convert the value a user inserts into our program into an integer:

to_review = int(input(“How many grades would you like to take into consideration? ”))

We’ve replaced float() with int(). Run our program and see if it works:

Venus profile photo

«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»

Venus, Software Engineer at Rockbot

How many grades would you like to take into consideration? 3

This student has earned a grade of over 75 2 times.

Our code works. Our code tells us that in the last three tests, a student has earned a grade of over 75 on two occasions.

Conclusion

The “TypeError: slice indices must be integers or None or have an __index__ method” error is raised when you try to slice a list using a value that is not an integer, such as a float.

To solve this error, make sure any values you use in a slicing statement are integers. Now you have the knowledge you need to fix this error like a professional Python coder!

When running the code in IDLE gives the following error:

Traceback (most recent call last):   File "C:/Python34/inversion3.py",
line 44, in <module>
    nInversions.inversionMergeSort(m)   File "C:/Python34/inversion3.py", line 16, in inversionMergeSort
     left = m[0:half] TypeError: slice indices must be integers or None or have an __index__ method

CODE:-

from collections import deque

m = []
f = open("IntegerArray.txt")
for line in f:
    m.append(int(line))

class InversionCount:

    def __init__(self, n):
        self.n = n
    def inversionMergeSort(self, m):
        if len(m) <= 1:
            return m
        half = len(m)/2
        left = m[0:half]
        right = m[half:]
        left = self.inversionMergeSort(left)
        right = self.inversionMergeSort(right)
        return self.inversionSort(left, right)

    def inversionSort(self, left, right):
        leftQueue = deque(i for i in left)
        rightQueue = deque(j for j in right)
        orderedList = []
        while len(leftQueue) > 0 or len(rightQueue) > 0:
            if len(leftQueue) > 0 and len(rightQueue) > 0:
                if leftQueue[0] <= rightQueue[0]:
                    orderedList.append(leftQueue[0])
                    leftQueue.popleft()
                else:
                    orderedList.append(rightQueue[0])
                    self.n += len(leftQueue)
                    rightQueue.popleft()
            elif len(leftQueue) > 0:
                orderedList.append(leftQueue[0])
                leftQueue.popleft()
            elif len(rightQueue) > 0:
                orderedList.append(rightQueue[0])
                rightQueue.popleft()
        return orderedList

nInversions = InversionCount(0)
nInversions.inversionMergeSort(m)
print (nInversions.n)

ApproachingDarknessFish's user avatar

asked Feb 2, 2015 at 6:38

jarvis's user avatar

1

In 3.x, int/int gives a float. which is not an int.

>>> 3/2
1.5

so your line 15

        half = len(m)/2

makes half a float. What you need is a double slash

        half = len(m)//2

to make half an int, as needed for its use in the slice in line 16.

answered Feb 2, 2015 at 7:19

Terry Jan Reedy's user avatar

Terry Jan ReedyTerry Jan Reedy

17.9k3 gold badges39 silver badges51 bronze badges

4

In your case, len(m)/2 returns a float and line 16 is expecting an int.

You should type cast half to int as the following:

left = m[0:int(half)]

Mohd's user avatar

Mohd

5,4687 gold badges18 silver badges30 bronze badges

answered Aug 22, 2017 at 23:16

Vittória Zago's user avatar

By only using / this will give you result in float you need to use // in order to give the result into integer.

This will resolve the error. It worked for me

answered Feb 28, 2022 at 13:25

Ajay Nikumbh's user avatar

When running the code in IDLE gives the following error:

Traceback (most recent call last):   File "C:/Python34/inversion3.py",
line 44, in <module>
    nInversions.inversionMergeSort(m)   File "C:/Python34/inversion3.py", line 16, in inversionMergeSort
     left = m[0:half] TypeError: slice indices must be integers or None or have an __index__ method

CODE:-

from collections import deque

m = []
f = open("IntegerArray.txt")
for line in f:
    m.append(int(line))

class InversionCount:

    def __init__(self, n):
        self.n = n
    def inversionMergeSort(self, m):
        if len(m) <= 1:
            return m
        half = len(m)/2
        left = m[0:half]
        right = m[half:]
        left = self.inversionMergeSort(left)
        right = self.inversionMergeSort(right)
        return self.inversionSort(left, right)

    def inversionSort(self, left, right):
        leftQueue = deque(i for i in left)
        rightQueue = deque(j for j in right)
        orderedList = []
        while len(leftQueue) > 0 or len(rightQueue) > 0:
            if len(leftQueue) > 0 and len(rightQueue) > 0:
                if leftQueue[0] <= rightQueue[0]:
                    orderedList.append(leftQueue[0])
                    leftQueue.popleft()
                else:
                    orderedList.append(rightQueue[0])
                    self.n += len(leftQueue)
                    rightQueue.popleft()
            elif len(leftQueue) > 0:
                orderedList.append(leftQueue[0])
                leftQueue.popleft()
            elif len(rightQueue) > 0:
                orderedList.append(rightQueue[0])
                rightQueue.popleft()
        return orderedList

nInversions = InversionCount(0)
nInversions.inversionMergeSort(m)
print (nInversions.n)

ApproachingDarknessFish's user avatar

asked Feb 2, 2015 at 6:38

jarvis's user avatar

1

In 3.x, int/int gives a float. which is not an int.

>>> 3/2
1.5

so your line 15

        half = len(m)/2

makes half a float. What you need is a double slash

        half = len(m)//2

to make half an int, as needed for its use in the slice in line 16.

answered Feb 2, 2015 at 7:19

Terry Jan Reedy's user avatar

Terry Jan ReedyTerry Jan Reedy

17.9k3 gold badges39 silver badges51 bronze badges

4

In your case, len(m)/2 returns a float and line 16 is expecting an int.

You should type cast half to int as the following:

left = m[0:int(half)]

Mohd's user avatar

Mohd

5,4687 gold badges18 silver badges30 bronze badges

answered Aug 22, 2017 at 23:16

Vittória Zago's user avatar

By only using / this will give you result in float you need to use // in order to give the result into integer.

This will resolve the error. It worked for me

answered Feb 28, 2022 at 13:25

Ajay Nikumbh's user avatar

@Esugi8

For training ZF Faster-rcnn with PASCAL VOC 2007 dataset,
I input the command as shown in the tutorial
./experiments/scripts/faster_rcnn_end2end.sh 0 ZF pascal_voc

Then I got an error below

Traceback (most recent call last):
File «./tools/train_net.py», line 112, in
max_iters=args.max_iters)
File «~ /py-faster-rcnn/tools/../lib/fast_rcnn/train.py», line 160, in train_net
model_paths = sw.train_model(max_iters)
File «~ /py-faster-rcnn/tools/../lib/fast_rcnn/train.py», line 101, in train_model
self.solver.step(1)
File «~ /py-faster-rcnn/tools/../lib/rpn/proposal_target_layer.py», line 66, in forward
rois_per_image, self._num_classes)
File «~ /py-faster-rcnn/tools/../lib/rpn/proposal_target_layer.py», line 191, in _sample_rois
_get_bbox_regression_labels(bbox_target_data, num_classes)
File «~ /py-faster-rcnn/tools/../lib/rpn/proposal_target_layer.py», line 127, in _get_bbox_regression_labels
bbox_targets[ind, start:end] = bbox_target_data[ind, 1:]
TypeError: slice indices must be integers or None or have an index method

I just followed the tutorial and did not edit any file.
Could you please let me know how to solve this issue?

—using software versions—
python2.7, Cuda-7.0, cuDNN4.0,

@bjornamr

@SietseHuisman

Same here. Checked train.prototxt, checked all annotations in my data..

Edit:

Seems like the latest version of numpy (1.12.0) does not support floats as indexes. From release notes:

Indexing with floats raises IndexError, e.g., a[0, 0.0].

Downgrading to numpy 1.11.0 worked for me.

Microos, alexdominguez09, Esugi8, salmanmaq, bclyc, deercoder, Kaze89, lixiang-ucas, tejus-gupta, lightjake, and 15 more reacted with thumbs up emoji
MaratSaidov reacted with thumbs down emoji
PapaMadeleine2022, Eezzeldin, kailashnagarajan, michoemad, deepakkochhar11, MisterDiabl0, aguptaneurala, and nc-BobLee reacted with laugh emoji
PapaMadeleine2022, dkasinets, Mrshantia, deepakkochhar11, MisterDiabl0, and aguptaneurala reacted with hooray emoji
PapaMadeleine2022, deepakkochhar11, aguptaneurala, and affian reacted with heart emoji
luthevy reacted with eyes emoji

@alexdominguez09

I had exactly the same error message. Solved by uninstalling numpy 1.12.0 and installing numpy 1.11.2.

Worked perfect for me.

@Esugi8

I really appreciate you all giving good advices.
I uninstalled numpy1.12.0, then installed numpy 1.11.1 and re-installed openCV2.4.13, matplotlib1.5.1.
As a result, all issues have been solved!!

@leejaymin

Thanks.
1.10 numpy, that’s ok

@tejus-gupta

@SietseHuisman has identified the error correctly(numpy v1.12.0 doesn’t support float indices)

An easier solution is to add the following lines to lib/proposal_target_layer.py
After line 126,

start=int(start)
end=int(end)

After line 166,

fg_rois_per_this_image=int(fg_rois_per_this_image)
Po-Hsuan-Huang, KeithWM, yuezhixiong, zszhong, helxsz, RobinPapke, samet-akcay, xiong-qiao, seanorar, truetqy, and 47 more reacted with thumbs up emoji
npochhi, nuoxu, Amberlan1001, JFishLover, and darcyzhc reacted with laugh emoji
JosephKJ, okanlv, nhatquang-tran, starxhong, yogsin, jzyztzn, clairelabitbonis, ZhangZhida, nuoxu, JFishLover, and darcyzhc reacted with hooray emoji
JosephKJ, okanlv, nhatquang-tran, lclin-china, starxhong, yogsin, jzyztzn, ZhangZhida, nuoxu, SureXs, and 2 more reacted with heart emoji
JFishLover and darcyzhc reacted with rocket emoji

@Po-Hsuan-Huang

I can confirm @tejus-gupta ‘s method worked on numpy 1.12.1.
I was running
./tools/train_net.py --gpu 0 --solver models/pvanet/example_finetune/solver.prototxt --weights models/pvanet/pva9.1/PVA9.1_ImgNet_COCO_VOC0712.caffemodel --iters 100000 --cfg models/pvanet/cfgs/train.yml --imdb voc_2007_trainval

@zhcf

Meet the same problem, fix it using tejus-gupta’s suggestion, it worked.

@sdews

I tried to downgrade numpy to version 1.11.2. But there was a new error
ImportError: numpy.core.multiarray failed to import.
I tried to solve this new error and failed. Finally, I upgrade numpy to the latest version 1.13.1 . And with @tejus-gupta ‘s method, I solve the error
TypeError: slice indices must be integers or None or have an index method.

@Xinying666

the same problem
I tried to downgrade numpy to version 1.11.2. But there was a new error
ImportError: numpy.core.multiarray failed to import.
I tried to solve this new error and failed. Finally, I upgrade numpy to the latest version 1.13.1 . however,I haven’t solved the problem:
TypeError: slice indices must be integers or None or have an index method.

@ShanQincheng

the same as @sdews ,but I there is one thing different.

My proposal_target_layer.py directory position is at lib/rcn/proposal_target_layer.py

@fengyuentau

@tejus-gupta ‘s method worked. Huge thanks.
But I think it’s better to refer the exact line code rather than line number, since the line number mentioned does not match the one I have.

In code block,

    for ind in inds:
        cls = clss[ind]
        start = 4 * cls
        end = start + 4
        bbox_targets[ind, start:end] = bbox_target_data[ind, 1:]
        bbox_inside_weights[ind, start:end] = cfg.TRAIN.BBOX_INSIDE_WEIGHTS

add the following two lines after end = start + 4,

        start = int(start)
        end = int(end)

Add line fg_rois_per_this_image = int(fg_rois_per_this_image) after code block,

    # Guard against the case when an image has fewer than fg_rois_per_image
    # foreground RoIs
    fg_rois_per_this_image = min(fg_rois_per_image, fg_inds.size)

And in my case, lib/proposal_target_layer.py should be lib/rpn/proposal_target_layer.py.

BTW, I am using numpy 1.14.0 and only one version of numpy is installed. By downgrading numpy version to 1.11.2, I met the same problem as @sdews. I googled this problem but found no working solutions. Most of them are suggesting uninstalling other versions of numpy. Maybe editing the path could make python pick up the right version of numpy, but I don’t know how to do this. Anyone who figures this out please let me know. Thanks.

UPDATE:
For those who don’t want to edit any code, downgrading numpy version to 1.11.0 will not help unless you recompile everything. I finally succeeded in using numpy-1.11.0 without editing any code just by cloning another copy of py-faster-rcnn and following the official installation guide again. I tried only make clean && make superclean under $FRCN_ROOT/caffe-fast-rcnn, but that did not help solve the problem. Also I tried to rebuild the Cython modules by command make under $FRCN_ROOT/lib, but it told me that everything is up-to-date which did not solve the problem too. Since step of building Cython modules did not offer any cleaning command like make clean, maybe deleting the whole current directory $FRCN_ROOT/lib and replacing it with its original one will help, which I have not yet tried. However, recompiling everything in another new copy will always work after downgrading numpy.

@tacsam1212

@Fung-yuantao I am new to Python and new to Github so straightaway, I apologize for the lack of the formatting standard. I am having this same issue as above, and am using numpy 1.14.0. However I can’t find where the code is I need to add that you mentioned above. Basically, I can’t find lib/rpn/proposal_target_layer.py. Could you explain how to find it?

Here is my error message:

TypeError Traceback (most recent call last)
in ()
—-> 1 spectrogram = violin.make_spectrogram(seg_length=1024)
2 spectrogram.plot(high=5000)

~Anaconda3libsite-packagesthinkdsp.py in make_spectrogram(self, seg_length, win_flag)
941
942 while j < len(self.ys):
—> 943 segment = self.slice(i, j)
944 if win_flag:
945 segment.window(window)

~Anaconda3libsite-packagesthinkdsp.py in slice(self, i, j)
895 j: second slice index
896 «»»
—> 897 ys = self.ys[i:j].copy()
898 ts = self.ts[i:j].copy()
899 return Wave(ys, ts, self.framerate)

TypeError: slice indices must be integers or None or have an index method

@fengyuentau

@tacsam1212 Assuming that you are using the up-to-date py-faster-rcnn, the file is located in py-faster-rcnn/lib/rpn/ as the following picture. Or you can use find command to search for it on Linux.
image

But I think what your are dealing with is another project , which is not py-faster-rcnn, and for sure you cannot find that file. Errors you got are similar though. You should really read the last part in your error message. Guess j is other type like float, but the type of index in numpy 1.14.0 must be integer. Maybe you should turn type of j to be integer before you are using it as index.

@tacsam1212

@Fung-yuantao I don’t see how/where to change the type. Here is the code from where it is saying the error is originating from:

def make_spectrogram(self, seg_length, win_flag=True):
    """Computes the spectrogram of the wave.

    seg_length: number of samples in each segment
    win_flag: boolean, whether to apply hamming window to each segment

    returns: Spectrogram
    """
    if win_flag:
        window = np.hamming(seg_length)
    i, j = 0, seg_length
    step = seg_length // 2

    # map from time to Spectrum
    spec_map = {}

    while j < len(self.ys):
        segment = self.slice(i, j)
        if win_flag:
            segment.window(window)

        # the nominal time for this segment is the midpoint
        t = (segment.start + segment.end) / 2
        spec_map[t] = segment.make_spectrum()

        i += step
        j += step
        
    return Spectrogram(spec_map, seg_length)

And the second: Lines 891 — 900

def slice(self, i, j):
    """Makes a slice from a Wave.

    i: first slice index
    j: second slice index
    """
    ys = self.ys[i:j].copy()
    ts = self.ts[i:j].copy()
    
    return Wave(ys, ts, self.framerate)

How do you change the type of index?

Thanks in advance

@fengyuentau

@tacsam1212 In slice, change type of j like the following:

def slice(self, i, j):
    """Makes a slice from a Wave.

    i: first slice index
    j: second slice index
    """
    j = (int) j # Change type of j to be integer
    ys = self.ys[i:j].copy()
    ts = self.ts[i:j].copy()
    
    return Wave(ys, ts, self.framerate)

@rh01

@SietseHuisman has identified the error correctly(numpy v1.12.0 doesn’t support float indices)

An easier solution is to add the following lines to lib/proposal_target_layer.py
After line 126,

start=int(start)
end=int(end)

After line 166,

fg_rois_per_this_image=int(fg_rois_per_this_image)

@tejus-gupta ‘s method worked on numpy 1.16.

I tired to run this program, but it would give me the above error on line 15
the program supposed to evaluate a preorder arithmetic expressions where it takes a single expression from stdin and output the result

return (preOrder( lst [ 1 : ( (len(lst)+1)/2) ] )  +   preOrder( lst [ (len(lst) + 1)/2 : ] ))

here is my program

def preOrder(lst) :
        if len(lst) == 3 :
            if lst[0] == '+' :
                return lst[1] + lst[2]
            elif lst[0] == '-' :
                return lst[1] - lst[2]
            elif lst[0] == '*' :
                return lst[1] * lst[2]
            elif lst[0] == '/' :
                return lst[1] / lst[2]
            elif lst[0] == '%' :
                return lst[1] % lst[2]
        else :
            if lst[0] == '+' :
                return (preOrder( lst [ 1 : ( (len(lst)+1)/2) ] )  +   preOrder( lst [ (len(lst) + 1)/2 : ] ))
            elif lst[0] == '-' :
                return preOrder( lst [ 1 : ( (len(lst)+1)/2) ] )  -   preOrder( lst [ (len(lst) + 1)/2 : ] )
            elif lst[0] == '*' :
                return preOrder( lst [ 1 : ( (len(lst)+1)/2) ] )  *   preOrder( lst [ (len(lst) + 1)/2 : ] )
            elif lst[0] == '/' :
                return preOrder( lst [ 1 : ( (len(lst)+1)/2) ] )  /   preOrder( lst [ (len(lst) + 1)/2 : ] )
            elif lst[0] == '%' :
                return preOrder( lst [ 1 : ( (len(lst)+1)/2) ] )  %   preOrder( lst [ (len(lst) + 1)/2 : ] )
    pre = ['+', '+', 6, 3, '-', 8, 4]
    print ("preorder:")
    print (pre)
    print (preOrder(pre))

Chanda Korat's user avatar

Chanda Korat

2,3832 gold badges18 silver badges23 bronze badges

asked Mar 7, 2017 at 11:18

Golden.Beta's user avatar

0

Assumption: You’re running Python 3 (or Python 2 with from __future__ import division in effect). On Python 3, the / operator is «true» division, and the result, even for int operands, is always a float, which is not a valid slice index.

If you want C-like truncating division (technically, floor division, but the difference is irrelevant for positive numbers), use the // operator, which for int operands produces the rounded down result of the division as an int. // is available on Python 2 as well (with or without the __future__ import) and can be used there to make it unambiguous that you want floor division, easing porting to Python 3.

That is, change every instance of (len(lst)+1)/2 to (len(lst)+1) // 2.

answered Mar 7, 2017 at 11:22

ShadowRanger's user avatar

ShadowRangerShadowRanger

137k12 gold badges174 silver badges258 bronze badges

0

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Skyway nano 2 ошибка l706
  • Skyway 350 dual pulse коды ошибок