0

As the question stated, I have one list contains x elements. For example the x is 4:

first_data = [1, 2, 3, 4]

I want to construct another list with a fix size of 8. This list will contain whatever first_data have. If the first_data do not have 8 elements, the rest of the elements will be 0.

Example:

final_data = [1, 2, 3, 4, 0, 0 ,0, 0]

So far I have tried different methods but it didn't work.

How can I achieve this? Thanks and appreciate if any helps!

user2390182
  • 72,016
  • 6
  • 67
  • 89
Sivvie Lim
  • 784
  • 2
  • 14
  • 43

4 Answers4

4

You could do the following, making use of max and len:

size = 8
final_data = first_data + [0] * max(0, size - len(first_data))
final_data
# [1, 2, 3, 4, 0, 0, 0, 0]

While this is very explicit, you can be more concise and use how list handles multiplication with negative numbers (e.g. [0] * -3 == []):

final_data = first_data + [0] * (size - len(first_data))

If you want to trim first_data down in case it is longer than size, just use first_data[:size] instead of first_data in any of the above examples.

user2390182
  • 72,016
  • 6
  • 67
  • 89
  • omg I totally didn't think of using the length of the data! Thank you so much for the answer and editing of the question!!! – Sivvie Lim Sep 26 '19 at 07:45
1

Simple.You can do it like this.

array = [0]*8
arr = [1, 2, 3, 4]
array[:len(arr)] = arr
Beeti Sushruth
  • 321
  • 2
  • 12
0

Let l be your list

You can initialise l like so:

fixed_size = 8
l = [0] * fixed_size
Ishan Joshi
  • 487
  • 3
  • 7
0

first, you need to know how many zeros are missing. to do so, compare the desired length to what you have:

from typing import List

def pad_with_zeros( initial: List, desired_len: int):

    zeros_to_add = desired_len - len(initial)

    if zeros_to_add > 0:
        padding = [0] * zeros_to_add
        return initial + padding
    else:
        # How do you want to handle the case when the initial list is longer than the desired output?
        pass

Then we create a new list of zeros, and extend the initial list using '+'. You will need to handle the case when initial list needs zero padding, or even is bigger than the desired fixed length.

ikamen
  • 3,175
  • 1
  • 25
  • 47
  • I do not know how many zeros are missing because the list is accepted from user value, they can filling it within a range but not constant number. – Sivvie Lim Sep 26 '19 at 07:47