Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) 

Questions...

  1. Can I count on tn-1 < tn for any (tn-1,tn) after I've created them this way? (Is ordering preserved?)
  2. Is it good practice to copy the original mdtimes list with list comprehensions? If not how should it be done?
  3. 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))]  

Thanks

like image 501
Pete Avatar asked Dec 01 '10 16:12

Pete


2 Answers

Both list and tuple are ordered.

dtg0, dtg1 = itertools.tee(mdtimes) next(dtg0) dtsegs = zip(dtg0, dtg1) 
like image 81
Ignacio Vazquez-Abrams Avatar answered Sep 21 '22 12:09

Ignacio Vazquez-Abrams


  1. 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.

  2. It's an acceptable method, but I have 2 alternate suggestions: Use the copy module, or use dtg1 = mdtimes[:].

  3. Sounds reasonable.

like image 38
moinudin Avatar answered Sep 19 '22 12:09

moinudin