What is a list compression in Python?

Gary Herron gherron at islandtraining.com
Mon Jan 18 19:36:45 EST 2010


Kit wrote:
> Thank you so much guys.
>
> Just out of curiosity: can I do something like this to "square all
> even numbers in the range 1-10"?
> print [x^2 for x in range (1,11) if x % 2 == 0]
>
> Or is there a better way of doing it? Thanks for the help, and I am
> really appreciate your help.
>   

That's a fine way to do it, although:
 
  xrange is slightly more efficient than range for large
  sets of values.  (This isn't such a large set for it to matter.)

  You can get range and xrange to count by two's, eliminating
  the need for the "if" portion in this case.

  The exponent operator is ** not ^, and  x*x is more efficient than x**2.

So.

print [x**2 for x in xrange(1,11,2)]

Gary Herron



> Kit.
>
> On 1月19日, 上午12時30分, Steven D'Aprano <st... at REMOVE-THIS-
> cybersource.com.au> wrote:
>   
>> On Mon, 18 Jan 2010 08:07:41 -0800, Kit wrote:
>>     
>>> Hello Everyone, I am not sure if I have posted this question in a
>>> correct board. Can anyone please teach me:
>>>       
>>> What is a list compression in Python?
>>>       
>> Google "python list comprehension".
>>
>> If Google is broken for you, try Yahoo, or any other search engine.
>>
>>     
>>> Would you mind give me some list compression examples?
>>>       
>> Instead of this:
>>
>> L = []
>> for x in range(10):
>>     L.append(x**2)
>>
>> you can write:
>>
>> L = [x**2 for x in range(10)]
>>
>> Instead of this example:
>>
>> L = []
>> for x in range(10):
>>     if x % 2 == 0:
>>         L.append(x**2)
>>
>> you can write:
>>
>> L = [x**2 for x in range(10) if x % 2 == 0]
>>
>> --
>> Steven
>>     
>
>   





More information about the Python-list mailing list