Adam Davies
Adam Davies

Reputation: 65

Python array reference variables elsewhere

Struggling to find an answer as I'm not sure on the exact wording I need so apologies.

Part of my script creates an array of values but I'm trying to reference these elsewhere to save speed. I have

def frame1():
  data = array.array('B' [1,2,3,4,5])

However I need to input 512 values into 720 frames and don't want to do this manually. I want to be able to make a variable thats

hour = 1,3,5
minute = 2,4,6

and combine them in a frame to have

data = array.array('B' [hour + minute + minute])

to result in

data = array.array('B' [1,3,5,2,4,6,2,4,6])

Hopefully that makes sense!!

Upvotes: 0

Views: 129

Answers (1)

chepner
chepner

Reputation: 530970

Both hour and minute are already lists, and so hour + minute is as well. You don't need to do anything special to make the new combined list from the sum; the sum is the combined list.

data = array.array('B', hour + minute + minute)

Strictly speaking, this is inefficient, as repeatedly concatenating two lists results in O(n^2) behavior. A better solution for more, longer lists would be to use itertools.chain.

from itertools import chain

data = array.array('B', chain(hour, minute, minute))

Depending on your actual code, this may or may not make an appreciable difference in the running time.

Upvotes: 2

Related Questions