quick beginners List comprehension question

Srinivasa NL nl.srinivas at gmail.com
Wed Jan 21 22:09:23 EST 2009


You can try this

import random

class foo:
  def __init__(self):
    self.bar = random.randint(1,100)


def getbar(ls,i):
  ls.append(foo())
  ls[i].bar = ls[i].bar * 3

ls = []

[getbar(ls,i) for i in range(10)]





On Thu, Jan 22, 2009 at 4:45 AM, Diez B. Roggisch <deets at nospam.web.de>wrote:

> 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
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090122/b6fc051d/attachment.html>


More information about the Python-list mailing list