Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Why is this code considered a generator?

I have a list called 'mb', its format is:

['Company Name', 'Rep', Mth 1 Calls, Mth 1 Inv Totals, Mth 1 Inv Vol, Mth 2 

...And so on

In the below code I simply append a new list of 38 0's. This is fine.

However in the next line I get an error: 'generator' object does not support item assignment

Can anyone tell me: 1) how to correct this error, and 2) why len(mb)-1 below is considered a generator.

Note: row[0] is merely a 'Company Name' held in another list.

mb.append(0 for x in range(38))
mb[len(mb)-1][0]=row[0]
like image 817
Phoenix Avatar asked May 10 '26 03:05

Phoenix


1 Answers

In fact, you do not append a list of 38 0s: you append a generator that will yield 0 38 times. This is not what you want. However, you can change can change mb.append(0 for x in range(38)) to

mb.append([0 for x in range(38)]) 
# note the [] surrounding the original generator expression!  This turns it
# into a list comprehension.

or, more simply (thanks to @John for pointing this out in the comments)

mb.append([0] * 38)
like image 147
Cody Piersall Avatar answered May 12 '26 16:05

Cody Piersall