Vinícius OA
Vinícius OA

Reputation: 357

Slice indices TypeError and Insert list method weird behavior

I have the following code:

a = [[0, 4]]
b = '1','2','3','4','5'
c = '*a3b*'

for f in b:
    if (f in c[a[0][0]:a[0][1]]):
        a[0].insert(0,f)

It returns:

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

But the slice indices are already integers, aren't they? What's going on? I also did (and worked, don't know why):

a[0].insert(0,int(f))

Upvotes: 0

Views: 42

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155734

After your loop has performed the insert once (for '3'), a has the value [['3', 0, 4]]. So the next time you try to slice, it's trying to slice c['3':0], where before it was slicing c[0:4].

Changing to a[0].insert(0,int(f)) made it "work" by making a's value [[3, 0, 4]], so the slice became c[3:0], which ends up slicing out nothing, but does it with valid integers. Your code logic looks very strange, but without knowing the goal, I can't provide any more suggestions beyond "You need to be more careful with your types" and "I'm not sure that insert is doing what you expect it to do".

Upvotes: 1

Related Questions