quick beginners List comprehension question

Diez B. Roggisch deets at nospam.web.de
Wed Jan 21 16:57:28 CET 2009


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.

Diez



More information about the Python-list mailing list