0

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.

Amol Shah
  • 15
  • 4

3 Answers3

0

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)]
C.Nivs
  • 12,353
  • 2
  • 19
  • 44
0

Please find below examples how to slice an array with 64 items into 8 slices of 8 items each. Please note the basic syntax [start:stop] and the slice indices are start <= i < stop, i.e. stop points one item after the slice.

test = list(range(64))

# example 1
for i in range(8):
    print(test[8*i:8*i+8])

# example 2
for i in range(0,64,8):
    print(test[i:i+8])
VPfB
  • 14,927
  • 6
  • 41
  • 75
0

You can use range

 for i in range(0, 64, 8):
      # slice arr[i: i + 8]

the result is

i, i+8
0 8
8 16
16 24
24 32
32 40
40 48
48 56
56 64
Chinny84
  • 956
  • 6
  • 16