Search code examples
pythonarraysobject-slicing

How to slice arrays in a for loop with the slicing indices variable


I want to slice an array of 64 items in eight parts and for that used the following method but it displayed a syntax error

for i in range(8):
    s = slice(8i,(8i+7))
    inparr = cornersort[s]

and

for i in range(8):
    inparr = cornersort[8i,(8i+7)]

Both show the Error message:

 s = slice(8i,(8i+7))
            ^
SyntaxError: invalid syntax

However when I removed the for loop iterable 'i'; the code worked. Please help how to fix this.


Solution

  • While 8i is a valid mathematical expression, it is not a valid python statement, since the multiplication operation needs to be explicit, not implied:

    i = 8
    
    8i # SyntaxError
    
    8*i
    64
    

    Furthermore, in variable names, they must not start with a number:

    2i = 5
    # syntaxError
    
    i2 = 5
    # this is fine
    

    So for your loop:

    for i in range(8):
        inparr = cornersort[8*i:(8*i+8)]