Javier Bezos wrote: > "Jacob Lee" <[EMAIL PROTECTED]> escribió en el mensaje > > satisfy some handy properties, the first of which being: > > l[:n] + l[n:] = l > > I don't think l[:5] + l[5:] = l is a handy property > and to me is clearly counterintuitive. Further,
It can be quite useful for inserting something into a list (or string), after finding the position where you wish to insert it. improvedList = l[:n] + [new stuff] + l[n:] I'm very fond of Python's slice indexing - it makes a number of things fairly easy, for example: myList[:N] # first N items myList[-N:] # last N items myList[start:start+N] # N items, from start position # chunk a list into smaller lists (or strings into smaller strings) # (thanks to Thorsten Kampe for the original example) def chunky(sequence, N): for i in range(len(sequence)/N + bool(len(sequence) % N)): print sequence[i*N:(i+1)*N] # no off-by-one errors here :-) myList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] N = 3 chunky(myList, N) which returns: [0, 1, 2] [3, 4, 5] [6, 7, 8] [9] Note you can leave out the bool part if you don't want that partial chunk at the end. I vaguely remember hearing at one stage that the sequence[position:position+length] notation is also potentially useful for indexing into large strings or buffers. Alex Martelli stated back in 2001, when this issue was previously discussed: > it IS just an extension of what Koenig > explains in his book "C Traps and Pitfalls", about how > always using half-open ranges helps avoid off-by-one > errors that otherwise tend to plague programs. Regards, Myles. -- http://mail.python.org/mailman/listinfo/python-list