There is some random class:
class MyClass: pass You need 1 line to create n objects of this class.
There is some random class:
class MyClass: pass You need 1 line to create n objects of this class.
n = 5 obj_list = [MyClass() for _ in range(n)] print(obj_list) To create n objects:
for _ in range(n): MyClass() To create and add n different objects to the list:
L = [MyClass() for _ in range(n)] To create a list where the same object repeats n times:
L = [MyClass()] * n This is more efficient and can be used if MyClass() is an immutable object in your task, for example, as numbers, strings, tuples in Python. Lazily, you can generate values using itertools.repeat(MyClass(), n) .
For simple types (like machine integers), there may be even more efficient options:
In [1]: n = 1000_000 In [2]: %timeit [1] * n 3.27 ms ± 28.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [3]: import array In [4]: %timeit array.array('Q', [1]) * n 829 µs ± 5.64 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) In [5]: import numpy In [6]: %timeit numpy.ones(n, dtype='Q') 730 µs ± 5.32 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) [1]*n is four times slower here than array('Q', [1])*n . numpy.ones(n, 'Q') is the fastest option presented.
Source: https://ru.stackoverflow.com/questions/806962/
All Articles