0

I'm sorry but semi-complicated array operations like this one are still awkward for me in Python.

I have an array in Python that I created with [0xff]*1024 and now I want to set subsequences of that to data ive calculated so lets say I've calculated [0x01,0x02,0x03,0x04] and want to place that within the first array at a particular position, say 10 bytes in.

So now my array should look like this:

[0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x01,0x02,0x03,0x04,0xff,0xff, ... ]

I still want the array to be 1024 bytes long. I need to insert several of these subsequences. So far I have:

a = [0xff]*1024
b = [0x01,0x02,0x03,0x04]

I'm not sure how to merge the two together. none of append, insert or extend are what I am looking for. b can be of arbitrary length.

Octopus
  • 8,075
  • 5
  • 46
  • 66

2 Answers2

2

You want list slicing:

a = [0xff]*1024
b = [0x01,0x02,0x03,0x04]
a[10:14] = b

This gets the four values between the tenth and the fourteenth values in a (inclusive), and changes them to the contents of b. There's no need to go a[10] = b[0];a[11] = b[1] (etc), because python already deals with this by unpacking the lists.

Community
  • 1
  • 1
TerryA
  • 58,805
  • 11
  • 114
  • 143
1

You're looking for slices.

a[10:14] = b

will replace a[10] with b[0], a[11] with b[1], a[12] with b[2], and a[13] with b[3].

Read the docs for more ;-)

Tim Peters
  • 67,464
  • 13
  • 126
  • 132