Python list with constant value
Asked Answered
I

3

14

I really love pythons possibility to shorten things up with its shorthand for loops — but sometimes, I need to obtain a list containing one value multiple times, which I did the following way:

plot(seconds, [z0 for s in seconds], '--')

But that unused s really disturbs me for aesthetic reasons.

Is there any shorter (and more beautiful) way of doing so? Like some special “multiplication” of some value?

Icbm answered 2/2, 2015 at 23:24 Comment(4)
You can multiply lists: [1] * 3 -> [1, 1, 1].Busybody
the usual name for unused variables is _, unless you can get rid of itEquatorial
although sometimes _ is for localizing strings... and other times it is a autopopulated context variable provided by the python shell ...Tradelast
@Equatorial and @Joran: I've always seen double-underscore __ used as a "junk" variable, specifically to avoid clashing with other uses of single-underscore _, like the interactive interpreter and the gettext module. As a bonus, while the leading underscore makes it invisible to from <module> import *, it's not quite long enough to trigger class-private name mangling.Formative
B
29

You mean like:

[z0] * len(seconds)
Bathrobe answered 2/2, 2015 at 23:27 Comment(4)
I had no clue this was a thing... Time to hit the basicsChassis
@AdamHughes As Joran Beasley said in his answer, the list is several references to the same object. So if the object can be mutated (like a list or dict), then the changes to one element be reflected for every other element (as they are the same object). However, this is safe if the object is immutable (such as strings or numbers, or a tuple).Bathrobe
Thanks for pointing that out, I wouldn't have realized that at all.Chassis
wow! who woulda thought.Ritualize
T
8

depending on what z0 is

 [z0]*len(seconds)

fair warning this will not work like you hope in the case that z0 is a mutable datatype

Tradelast answered 2/2, 2015 at 23:27 Comment(0)
C
1

I feel like the way you are doing it is not that dirty... But the numpy.fill function is a bit more tidy:

In [4]: import numpy as np
In [5]: x=np.empty(5)

In [6]: x.fill(8)

In [7]: x
Out[7]: array([ 8.,  8.,  8.,  8.,  8.])
Chassis answered 2/2, 2015 at 23:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.