-1

I'm actually trying to create a function to turn a bi-dimensionnal list at 90° on the left or the right (it must work for n line and n column). I found a way to do it with two loops "for", but it tells me that the generator is not subscriptable when I try to call that function. As I started Python one month ago, I don't have any idea of what a generator is, and I didnt undestand what I found on the net. By the way, I have troubles to research answers hidden in other posts because of the language.

Here's the code to turn to the right :

def Rotationversdroite(m,liste):
    i = 0
    x, y = 0, 0
    z = m - 1
    listebis = ([0]*(m) for i in range(m))
    for x in range(m):
        for y in range(m):
            listebis[y][z-x] = liste[x][y]
    return listebis
Thomas Baruchel
  • 7,236
  • 2
  • 27
  • 46
Raëgan
  • 25
  • 5

2 Answers2

1

You are assigning a generator to the listebisvariable with a generator expression.

Replace

listebis = ([0]*(m) for i in range(m))

with a list comprehension

listebis = [[0] * m for i in range(m)]
chepner
  • 497,756
  • 71
  • 530
  • 681
yanjost
  • 5,223
  • 2
  • 25
  • 28
1

in a nutshell generators are used in iteration (usually for loops) very similarly to lists or tuples but do not store every value for iteration at one time which can save on memory space.

when you write

listebis = ([0]*(m) for i in range(m))

it does not actually execute the loop and store every value at once, instead it sets up a process that can generate values based on the specified loop.

To run the loop and store the results in a list change the line to one of:

listebis = list([0]*(m) for i in range(m))
listebis = [[0]*(m) for i in range(m)]      #square brackets instead of round

on a side note, you don't have to initialize i,x, or y since they will be initialized at the start of their respective for loops.

Tadhg McDonald-Jensen
  • 20,699
  • 5
  • 35
  • 59