Get The Most Affordable Hosting in the World!

Starting at just $1.87/month, Vercaa offers unbeatable pricing for world-class web hosting services.

Fast, reliable, and secure hosting to power your website without breaking the bank. Plus, enjoy a free CDN for faster loading times worldwide!

Get Started Now!

List is a mutable data type in Python. It means, the contents of list can be modified in place, after the object is stored in the memory. You can assign a new value at a given index position in the list

Syntax

list1[i] = newvalue

Example 1

In the following code, we change the value at index 2 of the given list.

 
list3 = [1, 2, 3, 4, 5] print ("Original list ", list3) list3[2] = 10 print ("List after changing value at index 2: ", list3)

It will produce the following output −

Original list [1, 2, 3, 4, 5]
List after changing value at index 2: [1, 2, 10, 4, 5]

You can replace more consecutive items in a list with another sublist.

Example 2

In the following code, items at index 1 and 2 are replaced by items in another sublist.

 
list1 = ["a", "b", "c", "d"] print ("Original list: ", list1) list2 = ['Y', 'Z'] list1[1:3] = list2 print ("List after changing with sublist: ", list1)

It will produce the following output −

Original list: ['a', 'b', 'c', 'd']
List after changing with sublist: ['a', 'Y', 'Z', 'd']

Example 3

If the source sublist has more items than the slice to be replaced, the extra items in the source will be inserted. Take a look at the following code −

 
list1 = ["a", "b", "c", "d"] print ("Original list: ", list1) list2 = ['X','Y', 'Z'] list1[1:3] = list2 print ("List after changing with sublist: ", list1)

It will produce the following output −

Original list: ['a', 'b', 'c', 'd']
List after changing with sublist: ['a', 'X', 'Y', 'Z', 'd']

Example 4

If the sublist with which a slice of original list is to be replaced, has lesser items, the items with match will be replaced and rest of the items in original list will be removed.

In the following code, we try to replace "b" and "c" with "Z" (one less item than items to be replaced). It results in Z replacing b and c removed.

 
list1 = ["a", "b", "c", "d"] print ("Original list: ", list1) list2 = ['Z'] list1[1:3] = list2 print ("List after changing with sublist: ", list1)

It will produce the following output −

Original list: ['a', 'b', 'c', 'd']
List after changing with sublist: ['a', 'Z', 'd']





The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.
Was this answer helpful? 1 Users Found This Useful (1 Votes)