-1

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.

  • 1
    Does this answer your question? [Concatenating two lists - difference between '+=' and extend()](https://stackoverflow.com/questions/3653298/concatenating-two-lists-difference-between-and-extend) – TYZ May 02 '22 at 16:03

3 Answers3

3

You can use list concatenation:

x_new = [0.0] * 4 + x

or

x_new = [0.0 for _ in range(4)] + x
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
0

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".

FLAK-ZOSO
  • 3,873
  • 4
  • 8
  • 28
  • 1
    Repeatedly inserting elements in the first position of the list requires constantly moving memory. I don't recommend this usage. – Mechanic Pig May 02 '22 at 16:07
0

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.

Olivia Smith
  • 45
  • 2
  • 7