Can I count on order being preserved in a Python tuple?
I've got a list of datetimes from which I want to construct time segments. In other words, turn [t0, t1, ... tn] into [(t0,t1),(t1,t2),...,(tn-1, tn)]. I've done it this way:
# start by sorting list of datetimes mdtimes.sort() # construct tuples which represent possible start and end dates # left edges dtg0 = [x for x in mdtimes] dtg0.pop() # right edges dtg1 = [x for x in mdtimes] dtg1.reverse() dtg1.pop() dtg1.sort() dtsegs = zip(dtg0,dtg1)
- Can I count on tn-1 < tn for any (tn-1,tn) after I've created them this way? (Is ordering preserved?)
- Is it good practice to copy the original mdtimes list with list comprehensions? If not how should it be done?
The purpose for constructing these tuples is to iterate over them and segment a data set with tn-1 and tn. Is this a reasonable approach? i.e.
datasegment = [x for x in bigdata if ( (x['datetime'] > tleft) and (x['datetime'] < tright))]
Tuple order is as you insert values into the tuple. They're not going to be sorted as I think you're asking. zip will again, retain the order you inserted the values in.
It's an acceptable method, but I have 2 alternate suggestions: Use the copy module, or use dtg1 = mdtimes[:].
Both list and tuple are ordered.
dtg0, dtg1 = itertools.tee(mdtimes) next(dtg0) dtsegs = zip(dtg0, dtg1)