1.

How can we update and delete list in python.

Answer»

Updating Lists:

You can update single or multiple elements of lists by giving the slice on the lefthand side of the assignment operator, and you can add to elements in a list with the append() method. Following is a simple example:

# !/user/bin/python

list = [‘physics’, ‘chemistry’, 1997, 2000];

print “Value available at index 2 :”

print list[2];

list [2] = 2001;

print “New value available at index 2 :”

print list [2];

When the above code is executed it produces the following result:

Value available at index 2 :

1997

New value available at index 2 :

2001

Delete List Elements:

To remove a list element, you can use either the del statement if you know exactly which element(s) you are deleting of the remove() method if you do not know. Following is a simple example :

# !/user/bin/python

list1 = [‘physics’, ‘chemistry’, 1997, 2000];

print list1; del list1 [2];

print “After deleting value at index 2:”

print list1;

When the above code is executed, it produces the following result:

[‘physics’, ‘chemistry’, 1997, 2001]

After deleting value at index 2 :

[‘physics’, ‘chemistry’, 2000]



Discussion

No Comment Found