0

In Ruby I could say something like:

Array.new(5) { SomeClass.new }
# => [#<SomeClass:0x00007fb9bf053ba8>, #<SomeClass:0x00007fb9bf053b80>, #<SomeClass:0x00007fb9bf053b58>, #<SomeClass:0x00007fb9bf053b30>, #<SomeClass:0x00007fb9bf053b08>]

Is there an equivalent syntax in python?

Edit:

Not a duplicate of this, because this question asks for equivalent syntax and asks how to generate a list using an anonymous function (or similar), not how to build an empty list.

0112
  • 3,465
  • 6
  • 31
  • 54

1 Answers1

1

You can use a list comprehension for that:

[SomeClass() for _ in range(5)]

or if your use case allows it you can get an iterator with:

map(lambda _: SomeClass(), range(5))
Sergio Tulentsev
  • 219,187
  • 42
  • 361
  • 354