Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list with constant value

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?

like image 900
Lukas Juhrich Avatar asked Feb 02 '15 23:02

Lukas Juhrich


People also ask

How do you create an array with the same value in Python?

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.

How do you create a value list in Python?

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.


3 Answers

You mean like:

[z0] * len(seconds)
like image 51
Dunes Avatar answered Oct 05 '22 10:10

Dunes


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

like image 30
Joran Beasley Avatar answered Oct 05 '22 09:10

Joran Beasley


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.])
like image 21
Adam Hughes Avatar answered Oct 05 '22 09:10

Adam Hughes