'Create a byte array of all zeros except for a specified offset

bytearray(0x10)

This creates a byte array of all zeros with the length I want, but I want the same byte array except the 3rd b"\x00" is b"\xFF", so it's all zeros except for the third byte. How can I do this as simple and compact as possible?



Solution 1:[1]

The walrus operator does exactly what you want here, assuming you are going to assign you byte-array to a variable

Method

>>> (my_array := bytearray(0x10))[3] = 0xff
>>> my_array
bytearray(b'\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')

Why it works?

You can think of the walrus operator as an operator that will assign a thing to a variable and also return the thing. Since we are returning a mutable list, we can modify it on the same line. This would not work for something non-mutable.

In other words we are doing this:

>>> (my_array := bytearray(0x10))
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') 
# see? we get the array as return value. and its mutable so we can modify it.
# so on the same line we can just add the following mutation to the list
>>> my_array[3] = 0xff # returns nothing, this is mutation

Below we have an immutable example, a string operation that produces two outputs, one from the replace and one from assingment

>>> (foo := "foo").replace("foo","bar") # returns the replace action
'bar'
>>> foo # foo, however, remains unmutated since strings are immutable
'foo'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Markus Hirsimäki