Does Python copy references to objects when slicing a list? -


when list sliced, references contents copied original list? can imagine may not necessary, read opposite (mentioned in passing).

this question matters instance following idiom, in case of long my_list:

for (first_elmt, second_elmt) in itertools.izip(my_list[:-1], my_list[1:]):     … 

a copy use both memory and, presumably, time. compared looping on index of first_elmt xrange(), on list of 100 million integers. slicing approach 20% faster, seem copy references (the system time longer). indeed case?

ps: realize quite natural slices copy references: if original list modified, slice not change, easier have implementation of slice copy references of original list. pointer cpython implementation interesting, though.

slicing copy references. if have list of 100 million things:

l = [object() in xrange(100000000)] 

and make slice:

l2 = l[:-1] 

l2 have own backing array of 99,999,999 pointers, rather sharing l's array. however, objects pointers refer not copied:

>>> l2[0] l[0] true 

if want iterate on overlapping pairs of elements of list without making copy, can zip list iterator has been advanced 1 position:

second_items = iter(l) next(second_items, none) # avoid exception on empty input thing1, thing2 in itertools.izip(l, second_items):     whatever() 

this takes advantage of fact zip stops when input iterator stops. can extended cases you're working iterator using itertools.tee

i1, i2 = itertools.tee(iterator) next(i2, none) thing1, thing2 in itertools.izip(i1, i2):     whatever() 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -