I have a list which has length 1000. E.g., x = [1.0, 2.0, 3.0, 4.0, ..., 1000.0]. I would like to add 4 leading zero to above list. E.g. x_new = [0.0, 0.0, 0.0, 0.0, 1.0, 2.0, 3.0, ..., 1000.0]
I don't know how to add leading zeros to list. So, can you guys help me how to do it?
Thank you.
CodePudding user response:
You can use list concatenation:
x_new = [0.0] * 4 x
or
x_new = [0.0 for _ in range(4)] x
CodePudding user response:
The answer by BrokenBenchmark
is valid and working, but I would suggest a more pure solution:
x.insert(0, 0.0)
This appends a leading 0.0
at the beginning of x
, you just have to do this 4 times.
This is more pure because it edits x
without creating a new list
object.
I would suggest you to read this
and this
Edit
As Mechanic Pig
suggested in the comments, this is a very unefficient way of doing this, it's one of the least efficient ways of doing this, I'm suggesting it only because it "adds leading zeros to a list", instead of "creating a new list concatenating two lists of which the first one has 4 leading zeros".
CodePudding user response:
The answer by FLAK-ZOSO is very good, but in case you want to know how to properly iterate you can do this:
for i in range(4):
x.insert(0, 0.0)
Yes, this is not the most efficient thing as mentioned by Mechanic Pig, but I think that it's a lot more customizable and easy to understand.