newlist = [klass() * x]
[python] filling a list with new references
Whats the simplest way to fill a list with x number of separate instances of a class?
I tried this:
but that makes a list filled with x references to the same instance. I've been googling but I can't seem to find an answer. sorry if its a simple answer...
Thanks,
Bender
I'd probably go with the following solution:
There's most probably better ways to do it, but that's one of them.
newlist = [klass() for n in xrange(x)]
There's most probably better ways to do it, but that's one of them.
Quote:
for x in range(10000):
will generate a list of ten thousand elements, and will then loop through each of them in turn
for x in xrange(10000):
will genarate ten thousand integers one by one, passing each to the variable x in turn.
So the difference between range and xrange is what will make x different instances instead of x references to one instance?
The only difference between xrange and range is the way it generates the numeric range.
That list comprehension (read the tutorial on it) is kind of semantically equivalent to:
It just makes a range of x numbers and iterates over all of them, creating a klass instance for each one of them. What we iterate over doesn't really matter, as long as we do it a suitable number of times.
That list comprehension (read the tutorial on it) is kind of semantically equivalent to:
newlist = []for n in xrange(x): newlist.append(klass())
It just makes a range of x numbers and iterates over all of them, creating a klass instance for each one of them. What we iterate over doesn't really matter, as long as we do it a suitable number of times.
Quote:Original post by glBenderQuote:
for x in range(10000):
will generate a list of ten thousand elements, and will then loop through each of them in turn
for x in xrange(10000):
will genarate ten thousand integers one by one, passing each to the variable x in turn.
So the difference between range and xrange is what will make x different instances instead of x references to one instance?
No. Both will allow you to get different instances, because both, when used within the list comprehension (i.e. [klass() for x in...]) are a way of making the request "give me an instance" x-many times. The construct [klass()] * x only makes the request once, and copies the reference; that's how list multiplication is defined. (It *has* to be defined that way, because it's "multiplying" an already-existing thing, and doesn't know how that thing was created, so it can't just repeat the steps for creating it - it has to make a copy, and because Python objects have reference semantics, it copies the reference.)
For more complicated situations, you may be interested in the copy module.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement