[Tutor] Another list comprehension question

Smith, Jeff jsmith at medplus.com
Tue Feb 27 19:39:15 CET 2007

-----Original Message-----
From: jfouhy at gmail.com [mailto:jfouhy at gmail.com] On Behalf Of John Fouhy
Sent: Monday, February 26, 2007 4:00 PM
To: Smith, Jeff
Cc: tutor at python.org
Subject: Re: [Tutor] Another list comprehension question

On 27/02/07, Smith, Jeff <jsmith at medplus.com> wrote:
>> I'm probably missing something simple here but is there anyway to 
>> accomplish the following with a list comprehension?
>> def get_clists():
>>     return [1, 2, 3]
>> def get_clist(num):
>>     if num == 1:
>>         return ['a', 'b', 'c']
>>     if num == 2:
>>         return ['x', 'y', 'z']
>>     if num == 3:
>>         return ['p', 'q']

>This would be better represented as a dictionary:
>>>> clists = { 1:['a', 'b', 'c'],
>...            2:['x', 'y', 'z'],
>...            3:['p', 'q'] }

This was a mockup from a much larger code fragment where the
get_clists() and get_clist() functions are part of an API to a CMS
system which return lists constructed from calls into the CMS system.

>> files = list()
>> for clist in get_clists():
>>     files += get_clist(clist)

>Just a comment -- you could write this as
"files.extend(get_clist(clist))", which would be slightly more

>This will do it:
>Or [x for k in get_clists() for x in get_clist(k)] using your original

I realize however that this is probably much less efficient since you
are iterating over the inner list rather than just taking it on in


More information about the Tutor mailing list