user2426316
user2426316

Reputation: 7331

How can I split a 8 byte array into two four byte arrays in Python?

what would be the fastest way to put the first 4 bytes of an 8 byte array in one array and the last 4 bytes in another one.

My approach was to create a for loop and then extract everything. Like this

for i in range(0,7):
    if i < 4:
        ...
    else
        ...

There has to be something more efficient. What am I missing?

Upvotes: 0

Views: 605

Answers (4)

Martino Dino
Martino Dino

Reputation: 585

List slicing is your friend here ;)

array = [0,1,2,3,4,5,6,7]

firstpart,secondpart = (array[:4],array[4:])

print firstpart
[0, 1, 2, 3]
print secondpart
[4, 5, 6, 7]

Upvotes: 0

Lazybeem
Lazybeem

Reputation: 105

a = range(0,8)
b = a[:4]
c = a[4:]

Easiest way I know.

Upvotes: 1

Tim Peters
Tim Peters

Reputation: 70735

Try

hi, lo = some_array[:4], some_array[4:]

Upvotes: 1

Steve Barnes
Steve Barnes

Reputation: 28405

Use slices:

A = [1,2,3,4,5,6,7,8]
A[0:4]
A[4:8]

Upvotes: 0

Related Questions