Public Group

# [python] filling a list with new references

This topic is 4233 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Whats the simplest way to fill a list with x number of separate instances of a class? I tried this:
newlist = [klass() * x]


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

##### Share on other sites
I'd probably go with the following solution:
newlist = [klass() for n in xrange(x)]

There's most probably better ways to do it, but that's one of them.

##### Share on other sites
Quote:
 for x in range(10000):will generate a list of ten thousand elements, and will then loop through each of them in turnfor 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?

##### Share on other sites
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:
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.

##### Share on other sites
Oh ok I think I get it. What tutorial are you referring to with 'the tutorial' ?

##### Share on other sites
Quote:
Original post by glBender
Quote:
 for x in range(10000):will generate a list of ten thousand elements, and will then loop through each of them in turnfor 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.

1. 1
2. 2
3. 3
Rutin
16
4. 4
5. 5

• 12
• 26
• 10
• 11
• 9
• ### Forum Statistics

• Total Topics
633723
• Total Posts
3013545
×