== Python synergies in list addressing Something I took from this Ian Bicking [[entry|http://blog.ianbicking.org/the-unbridled-humanity-of-apis.html]] is that synergies and elegance don't just happen; someone usually worked hard to make it all come out neatly. Python lists have an interesting case of this; some apparently odd decisions in other places turn out to be needed to create useful (and [[error-avoiding|OnInterfaceStyles]]) synergies. Python lists (and sequences in general) are indexed from 0. Zero-based indexing presents a problem, which can be succinctly stated as this: list element indexes run from 0 to _len(lst)~~-1~~_. That _-1_ is ugly and error prone. So Python has quietly arranged things so that you never have to write it (or _+1_, its kissing cousin), by making 'slice' addressing of lists and _range()_ end-exclusive asymmetric (instead of '_i:j_' running from _i_ to _j_, it runs from _i_ to _j-1_). This means: * _range(len(lst))_ generates indexes that exactly cover the list, since they run from 0 to _len(lst)-1_. * _lst[:len(lst)]_ is the entire list. * if _pref_ is at the start of the list, _lst[len(pref):]_ is the list with _pref_ removed from the start. * if _sublst_ is in _lst_ starting at _pos_, _lst[:pos]_ is everything before _sublst_ and _lst[pos + len(sublst):]_ is everything after _sublst_. * if _suf_ is at the end of _lst_, _lst[:-len(suf)]_ is the list with _suf_ removed from the end. * avoiding a subtler error, _lst[len(pref):]_ works even if _pref_ is zero length (although _lst[:-len(suf)]_ does not; can't win them all). All of these are straightforward expressions, with nary a stray _-1_ or _+1_ in sight and no chance for off by one errors. (Is it elegant or does the asymmetry cancel out the lack of _+1_ and _-1_? That's in the eye of the beholder, but I like it.) Python is not the first language to notice this issue; Scheme's _substring_ is end-exclusive, for example. Other things duck the issue by having their substring operation take a start and a length, instead of a start and and end position. (This entry's genesis came from comments made on AClosureConfusion.)