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.

kingsfoil
  • 3,795
  • 7
  • 32
  • 56

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
  • 226,338
  • 43
  • 373
  • 367