What's the Pythonic way to append to a bytearray a list?

19.3k Views Asked by At

I'm trying to append the contents of a list (which only contains hex numbers) to a bytearray. Right now I'm doing this and it works:

payload = serial_packets.get()
final_payload = bytearray(b"StrC")
final_payload.append(len(payload))
for b in payload:
   final_payload.append(b)

However, I believe it's not very Pythonic. Is there a better way to do this?

tldr; How can I append payload to final_payload in a more Pythonic way?

1

There are 1 best solutions below

0
On BEST ANSWER

You can extend, you don't need to iterate over payload:

final_payload.extend(payload)

Not sure you want final_payload.append(len(payload)) either.