0

I have to translate a java lib into a python one.

During that process i came across the arrays.copyOf() function (the one for bytes not string).

From Docs:

public static byte[] copyOf(byte[] original, int newLength)

Returns: a copy of the original array, truncated or padded with zeros to obtain the specified length

I would like to know if there is a built in equivalent of it or if there is a lib that does it.

my_data[some_int:some_int] is the equivalent of java copyOfRange() Here I need to output specific length bytes or byte array that will be padded with 0 if too short

Ch3steR
  • 20,090
  • 4
  • 28
  • 58
Bastien B
  • 1,018
  • 8
  • 25
  • Hey @Bastien B, is this what you are looking for? https://www.geeksforgeeks.org/python-list-copy-method/ – Rutangaba Nov 19 '21 at 14:29
  • 1
    @VictorSaraivaRocha `array.copyOf` has 2 arguments. The second argument specifies the length of the new array. – Ch3steR Nov 19 '21 at 14:34
  • 1
    @Bastien I have edited your question. Feel free to revert the changes if not ok. – Ch3steR Nov 19 '21 at 14:53

1 Answers1

3

We can do this in two steps,

  • Create a copy of the given list.
  • We can use slice assignment to return a list of size specified by the second arg.
def copy_of(lst, length):
    out = lst.copy() # This is a shallow copy. 
                     # For deepcopy use `copy.deepcopy(lst)`
    out[length:] = [0 for _ in range(length - len(lst))]
    return out

l = [1, 2, 3]
print(copy_of(l, 5))
# [1, 2, 3, 0, 0]

print(copy_of(l, 2))
# [1, 2]
Ch3steR
  • 20,090
  • 4
  • 28
  • 58