Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 763
Pepedou Avatar asked Jun 09 '15 18:06

Pepedou


People also ask

How do you append byte?

To concatenate multiple byte arrays, you can use the Bytes. concat() method, which can take any number of arrays.

How do you add bytes together in Python?

To join a list of Bytes, call the Byte. join(list) method. If you try to join a list of Bytes on a string delimiter, Python will throw a TypeError , so make sure to call it on a Byte object b' '. join(...)

What is the difference between bytes and Bytearray in Python?

The bytes() function returns a bytes object. It can convert objects into bytes objects, or create empty bytes object of the specified size. The difference between bytes() and bytearray() is that bytes() returns an object that cannot be modified, and bytearray() returns an object that can be modified.


1 Answers

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.

like image 93
Padraic Cunningham Avatar answered Sep 24 '22 04:09

Padraic Cunningham