When you type (foo for i in bar)
you get a generator, when you type [foo for i in bar]
you get a list. The difference between these two is that the generator create elements (generate) as it is traversed, while a list hold all items on memory. This is why (i for i in range(10))[2]
is not possible, while [i for i in range(10)][2]
is.
You should use generators when the whole set of items are too big to keep in memory or simply when you don't need them all in memory at same time. They are good for traversing files while keeping constant memory usage for example.
Now if you want to subscript something, like foo[some_index]
then foo
need to be subscriptable and generators aren't because doing so would throw away the whole point of generator existence. While someone may arg that (i for i in range(10))[2]
is okay, expanding some generators may end up in infinite loop, for example:
from itertools import count
even = (i for i in count() if i % 2 == 0)
This is perfect valid code. The count()
returns an infinite generator. If we can argue that even[1]
would be 2
what would be even[-1]
? There is no last even number. So the computation would take forever.
Anyway. Generators are common in python and sooner or later you'll need to convert then to a list or a tuple, you can do this by passing they to the list or tuple constructor list(range(10))
or tuple(range(10))
.
Now I think that we have enough background to answer your question. You are doing this testList = [(test("empty") for i in range(3)) for j in range(2)]
which gives us a list of generators. So testList[m][n]
reduces to something like (test("empty") for i in range(3))[n]
which is where things blow up.
If you just replace parenthesis by brackets you solve your problem, so testList = [[test("empty") for i in range(3)] for j in range(2)]
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…