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

3
  • Hey @Bastien B, is this what you are looking for? geeksforgeeks.org/python-list-copy-method Commented Nov 19, 2021 at 14:29
  • 1
    @VictorSaraivaRocha array.copyOf has 2 arguments. The second argument specifies the length of the new array. Commented Nov 19, 2021 at 14:34
  • 1
    @Bastien I have edited your question. Feel free to revert the changes if not ok. Commented Nov 19, 2021 at 14:53

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

1 Comment

thank you @Ch3steR, i ended up using it with a bytearray lst and it worked like a charm :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.