Assign value to a slice of a list

Assign value to a list slice

We can assign to slices.


name = list('java2s.com') 
print name 
name[2:] = list('ruby') 
print name 

The code above generates the following result.

Assign to several positions at once.


name = list('Perl') 
name[1:] = list('ython') 
print name 

The code above generates the following result.

Slice assignments can even be used to insert elements without replacing any of the original ones:


numbers = [1, 5] 
numbers[1:1] = [2, 3, 4] 
print numbers 

The code above generates the following result.

You can do the reverse to delete a slice:


numbers = [1, 2, 3, 4, 5] 
numbers[1:4] = [] 
print numbers 

The code above generates the following result.





















Home »
  Python »
    Data Types »




Data Types
String
String Format
Tuple
List
Set
Dictionary