Python list extend functionality using slices -
i'm teaching myself python ahead of starting new job. django job, have stick 2.7. such, i'm reading beginning python hetland , don't understand example of using slices replicate list.extend()
functionality.
first, shows extend
method by
a = [1, 2, 3] b = [4, 5, 6] a.extend(b)
produces [1, 2, 3, 4, 5, 6]
next, demonstrates extend slicing via
a = [1, 2, 3] b = [4, 5, 6] a[len(a):] = b
which produces exact same output first example.
how work? has length of 3, , terminating slice index point empty, signifying runs end of list. how b
values added a
?
python's slice-assignment syntax means "make slice equal value, expanding or shrinking list if necessary". understand may want try out other slice values:
a = [1, 2, 3] b = [4, 5, 6]
first, lets replace part of a
b
:
a[1:2] = b print(a) # prints [1, 4, 5, 6, 3]
instead of replacing values, can add them assigning zero-length slice:
a[1:1] = b print(a) # prints [1, 4, 5, 6, 2, 3]
any slice "out of bounds" instead addresses empty area @ 1 end of list or other (too large positive numbers address point off end while large negative numbers address point before start):
a[200:300] = b print(a) # prints [1, 2, 3, 4, 5, 6]
your example code uses "accurate" out of bounds slice @ end of list. don't think code you'd use deliberately extending, might useful edge case don't need handle special logic.
Comments
Post a Comment