user3413108
user3413108

Reputation:

Creating an array of objects in python without having to append in a loop

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?

Upvotes: 0

Views: 74

Answers (2)

Jan Vlcinsky
Jan Vlcinsky

Reputation: 44092

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

or using repeat

from itertools import repeat

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

Upvotes: 1

user2555451
user2555451

Reputation:

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.

Upvotes: 3

Related Questions