quick beginners List comprehension question

MRAB google at mrabarnett.plus.com
Wed Jan 21 17:03:42 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!
> 
You could reduce that to:

for x in Newlist:
     x.bar *= 3

but I don't think you could do it with list comprehension.



More information about the Python-list mailing list