Benjamin Levy
Benjamin Levy

Reputation: 343

list comprehension creating nested lists

I'd like to create nested lists of days per month list per year list:

[[ 31, 29, 31, 30 ], [ 31, 28, 31, 30 ] ]

with

mm = [ 1, 2, 3, 4 ]
yy = [ 2012, 2013 ]

but my code:

[ [ result.append( calendar.monthrange( y, m )[ 1 ] ) for m in mm] for y in yy ]        

produces:

[31, 29, 31, 30,  31, 28, 31, 30 ]

Can someone please tell me what I've done wrong? Thanks. BSL

Upvotes: 3

Views: 723

Answers (1)

Hayley Guillou
Hayley Guillou

Reputation: 3973

So, I'm assuming the full code looks something like this:

result = []
[ [ result.append( calendar.monthrange( y, m )[ 1 ] ) for m in mm] for y in yy ]   
print(result)

The problem with your code is your understanding of list comprehension. List comprehension creates a list, so you shouldn't be appending anything to another list within that. Right now, you are only appending things to result and then printing result and now actually creating a list from the list comprehension.

Here is the equivalent of what you are doing right now:

result  = [ ]
for y in yy:
    for m in mm:
        result.append( calendar.monthrange( y, m )[ 1 ] )

Here is the equivalent of what you want to be doing:

result  = [ ]
for y in yy:
    year = []
    for m in mm:
        year.append( calendar.monthrange( y, m )[ 1 ] )
    result.append(year)

And here is the list comprehension version of that:

>>> result = [[calendar.monthrange( y, m )[ 1 ] for m in mm] for y in yy]
>>> print(result)

[[31, 29, 31, 30], [31, 28, 31, 30]]

Upvotes: 3

Related Questions