In this Page, We are Providing Python Programming – Deleting List Elements. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.
Python Programming – Deleting List Elements
Deleting list elements
To remove a list element, one can use either the del statement (if you know the element index to delete) or remove () method (if you do not know the element index, but the element itself, discussed in section 4.1.9). The following example depicts the deletion of an element using the del statement.
>>> a= [ ' spam ' , ' eggs ' , 100 , 1234 ] >>> del a [ 1 ] >>> a [ ' spam ' , 100 , 1234 ]
- Delete elements from a Numpy Array by value or conditions in Python
- Python Interview Questions on Data Types and Their in-built Functions
- np.delete(): Remove items/rows/columns from Numpy Array | How to Delete Rows/Columns in a Numpy Array?
The del statement can also be used to explicitly remove the entire list.
>>> a= [ ' spam ' , ' eggs ' , 100 , 1234 ] >>> del a >>> a Traceback ( most recent call last ) : File " <stdin> " , line 1 , in <module> NameError: name ' a ' is not defined
The following is an interesting case of the del statement:
>>> a= [ ' spam ' , ' eggs ' , 100 , 1234 ] >>> del a [ 1 ] , a [ 1 ] >>> a [ ' spam ' , 1234 ]
It should be noted that the same index is deleted twice. As soon as an element is deleted, the indices of succeeding elements are changed. So deleting an index element n times, would actually delete n elements.
It is also possible to delete multiple items from a list.
>>> a= [ ' spam ' , ' eggs ' , 100 , 1234 ] >>> a [ 1 : 3 ] = [ ] >>> a [ ' spam ' , 1234 ]
There might be a scenario in which multiple lists need to be swapped among themselves. This is can done easily using multiple assignments expression.
>>> a= [ 10 , 20 , 30 ] >>> b= [ 40 , 50 , 60 ] >>> c= [ 70 , 80 , 90 ] >>> a , b , c=c , a , b >>> a [ 70 , 80 , 90 ] >>> b [ 10 , 20 , 30 ] >>> c [ 40 , 50 , 60 ]