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?
Create an array with the same values using NumPy The full() function takes a parameter size and element respectively. Adding furthermore to it we can create an array of arrays just like a two-dimensional array. We can give here data type also by using dtype. Here all the elements will be Integer types.
Create Python Lists In Python, a list is created by placing elements inside square brackets [] , separated by commas. A list can have any number of items and they may be of different types (integer, float, string, etc.). A list can also have another list as an item. This is called a nested list.
You mean like:
[z0] * len(seconds)
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
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.])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With