When using a list, you can change its contents by assigning to either a particular item or an entire section:
L = ['test', 'Test', 'TEST!'] L[1] = 'book2s.com' # Index assignment print( L ) L[0:2] = ['eat', 'new'] # Slice assignment: delete+insert print( L ) # Replaces items 0,1 # from w ww. j a va 2s . c o m
Both index and slice assignments are in-place changes.
They modify the subject list directly, rather than generating a new list object for the result.
Index assignment in Python replaces the single object reference at the designated offset with a new one.
Slice assignment replaces an entire section of a list in a single step.
L = [1, 2, 3] L[1:2] = [4, 5] # Replacement/insertion print( L ) L[1:1] = [6, 7] # Insertion (replace nothing) print( L ) L[1:2] = [] # Deletion (insert nothing) print( L )
In-place concatenation at the front of the list:
L = [1] L[:0] = [2, 3, 4] # Insert all at :0, an empty slice at front print( L ) L[len(L):] = [5, 6, 7] # Insert all at len(L):, an empty slice at end print( L ) L.extend([8, 9, 10]) # Insert all at end, named method print( L )