In this Page, We are Providing Python Programming – Updating List Elements. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.
Python Programming – Updating List Elements
Updating list elements
It is possible to change individual or multiple elements of a list:
>>> a= [ ' spam ' , ' eggs ' , 100 , 1234 ] >>> a [ 0 ]= ' filter ' >>> a [ ' filter ' , ' eggs ' , 100 , 1234 ] >>> a [ 2 : 4 ]= 455 , 56858 >>> a [ ' filter ' , ' eggs ' , 455 , 56858 ]
The items of list can be updated by the elements of another iterable (list, tuple).
>>> a= [ 66 . 25 , 333 , 333 , 1 , 1234 . 5 ] >>> b=[ ' hi ' , ' bye ' ] >>> a [ 2 : 4 ] =b >>> a [ 66 . 25 , 333 , ' hi ' , ' bye ' , 1234 . 5 ] >>> a= [ 66 . 25 , 333 , 333 , 1 , 1234 . 5 ] >>> b= ( ' hi ' , ' bye ' ) >>> a [ 2 : 4 ]=b >>> a [ 66 . 25 , 333 , ' hi ' , ' bye ' , 1234 . 5 ] >>> a= [ 66 . 25 , 333 , 333 , 1 , 1234 . 5 ] >>> b= [ ' hi ' , ' bye ' ] >>> a [ 1: 4 : 2 ] =b >>> a [ 66 . 25 , ' hi ' , 333 , ' bye ' , 1234 . 5 ]
It is also possible to insert elements in a list.
>>> a=[ ' spam ' , ' eggs ' , 100 , 1234 ] >>> a [ 1 : 1 ]=[ ' chair ' ] >>> a [ ' spam ' , ' chair ' , ' eggs ' , 100 , 1234 ] >>> a [ 1 : 1 ] = [ ' hello ', ' bye ' ] >>> a [ ' spam ' , ' hello ' , ' bye ' , ' chair ' , ' eggs ' , 100 , 1234 ]
To insert a copy of the list at the beginning of itself:
>>> a= [ ' spam ' , ' eggs ' , 100 , 1234 ] >>> a [ : 0 ]=a >>> a [ ' spam ' , ' eggs ' , 100 , 1234 , ' spam ' , ' eggs ' , 100 , 1234 ]
There are various methods of list objects for updating the list, which is discussed in section 4.1.9.