quick beginners List comprehension question
Philip Semanchuk
philip at semanchuk.com
Wed Jan 21 11:18:49 EST 2009
On Jan 21, 2009, at 10:52 AM, 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!
Other answers have been good; to them I'll add the comment that list
comprehensions are for *constructing* lists, not manipulating the
elements thereof.
HTH
Philip
More information about the Python-list
mailing list