quick beginners List comprehension question

Diez B. Roggisch deets at nospam.web.de
Wed Jan 21 18:15:17 EST 2009


MRAB schrieb:
> Diez B. Roggisch wrote:
>> Dr Mephesto wrote:
>>
>>> Hi,
>>> Im new to python, and OOP, and am trying to get a handle on list
>>> comprehension.
>>>
>>> Say I have a class Foo with a property called bar:
>>>
>>> class Foo:
>>>     def __init__(self):
>>>         self.bar = random.randint(1,100)
>>>
>>> and then I make a list of these objects:
>>>
>>> Newlist = []
>>> for x in range(10):
>>>     Newlist.append(Foo())
>>>
>>> Now, suppose I wanted to triple the value of 'bar', I could always do:
>>>
>>> for x in range(10):
>>> Newlist[x].bar = Newlist[x].bar * 3
>>>
>>> but can I do this using list comprehension?  Thanks in Advance!
>>
>> No, as such, because list-comprehensions require you to have an 
>> *expression*
>> in front of the iteration:
>>
>> resultlist = [<expr> for <variable(s)> in <iterable>]
>>
>> Now what you of course can do is this:
>>
>> def multiply(item):
>>     item.bar = item.bar * 3
>>
>> [multiply(i) for i in items]
>>
>> However, doing this will make python produce a list of None-references -
>> which is a waste. It's up to you if you care about that, but generally it
>> is frowned upon because of that, and the fact that the conciseness of the
>> list-comp here isn't really helping with the readability.
>>
> If you had:
> 
> def multiply(item):
>     item.bar = item.bar * 3
>     return item
> 
> then:
> 
> [multiply(i) for i in items]
> 
> would return items. Still a bad idea, though, because you're using a 
> list comprehension for its side-effect.

And redundant, which was the reason I ommited it.

Diez



More information about the Python-list mailing list