Python - List Index and slice assignments

Introduction

When using a list, you can change its contents by assigning to either a particular item or an entire section:

Demo

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

Result

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.

Demo

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 )

Result

In-place concatenation at the front of the list:

Demo

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 )

Result