quick beginners List comprehension question
Terry Reedy
tjreedy at udel.edu
Wed Jan 21 17:14:18 EST 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())
Constructing this list is the appropriate place for a comprehension.
Newlist = [Foo() for _ in range(10)]
> 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
Use MRAB's replacement for this.
> but can I do this using list comprehension?
Don't, for reasons given by others.
tjr
More information about the Python-list
mailing list