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
--
http://mail.python.org/mailman/listinfo/python-list