0

I am trying to create an array of object. I am able to do it like this:

def MyClass(object):
    def __init__(self, number=0):
         self.number=number

my_objects = []

for i in range(100) :
    my_objects.append(MyClass(0))

I want, however, to create the array without the loop (because I think for a more complex object the appending can be very time consuming). Is there a way to achieve this?

1
  • Appending a complex object to a list is exactly as expensive as appending a simple object, since all that is appended is a reference to the object. Variables, lists, function calls, all these things only store and manipulate references. Unlike in, say, C++, if you don't explicitly make a copy of your object, there probably won't be a copy involved. Commented May 14, 2014 at 0:53

2 Answers 2

3

You could always use a list comprehension:

my_objects = [MyClass(0) for _ in range(100)]

If you are using Python 2.x, you should also replace range with xrange:

my_objects = [MyClass(0) for _ in xrange(100)]

This is because the latter computes numbers lazily where as the former creates an unnecessary list.

Sign up to request clarification or add additional context in comments.

3 Comments

In this case wouldn't it actually be ok to use range since range generates a list of items?
The list of numbers produced by range is a separate thing from the list of objects produced by the comprehension.
Ah... I thought range could be taken advantage of once ;)
1
my_objects = [MyClass(0) for i in range(100)]

or using repeat

from itertools import repeat

my_objects = map(MyClass, repeat(0, 100))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.