Is there a better way to create a list of None objects?

Matthieu Dartiailh m.dartiailh at gmail.com
Thu Aug 12 05:22:37 EDT 2021


You can achieve the same result by writing:
[None] * 8

Comparing both cases in IPython I get:

In [1]: %timeit list((None,)*8)
110 ns ± 0.785 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

In [2]: %timeit [None] * 8
88.2 ns ± 0.432 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops 
each)

So the list multiplication appears a bit faster.

Best

Matthieu

Le 8/12/2021 à 10:57 AM, Stephen Tucker a écrit :
> Hi,
>
> I thought I'd share the following piece of code that I have recently written
> (a) to check that what I have done is reasonable - even optimum,
> (b) to inform others who might be wanting to do similar things, and
> (c) to invite comment from the community.
>
> -------------------------------------------
>
> #
>
> # Yes: Create an empty list of Band Limits for this language
>
> #
>
> # Note. The rather complicated logic on the right-hand side of the
>
> #       assignment below is used here because none of the following
>
> #       alternatives had the desired effect:
>
> #
>
> # Logic             Effect
>
> #
>
> # [None * 8]        TypeError: unsupported operand type(s) for *: ...
>
> # [(None) * 8]      TypeError: unsupported operand type(s) for *: ...
>
> # [((None)) * 8]    TypeError: unsupported operand type(s) for *: ...
>
> # [(None,) * 8]     [(None, None, None, None, None, None, None, None)]
>
> # list ((None) * 8) TypeError: unsupported operand type(s) for *: ...
>
> #
>
> diclll_BLim [thisISO_] = list ((None,) * 8)
>
>
> -------------------------------------------
>
> Thanks in anticipation.
>
> Stephen Tucker.



More information about the Python-list mailing list