How expensive are list and tuple slicing?

Alex delete.this.part.alex.news at attbi.com
Mon May 12 22:12:00 EDT 2003


Does slicing a list allocate memory at the point of the slice, or does
python implement some sort of copy on write scheme to save memory?  How
about tuples (which are immutable)?

Example: The following snippet of code counts the number of items in a
sequence.  It is obviously a very stupid way of doing this.  Neither the
sequence, nor any of its slices, are ever modified.  How much memory does
it consume if the sequence is a list?  A tuple?  Is the behavior the same
on Python and Jython?

def count(sequence):
  if len(sequence)==1:
    return 1
  return count(sequence[:1])+ count(sequence[1:])







More information about the Python-list mailing list