Wednesday, 24 January 2024

Delete an element from a list using del statement

The del statement is used to remove values from a list at a specified index. Following this deletion, all the elements in the list positioned after the removed value are shifted up by one index.

Syntax

del list[index]

>>> fruits = ['Apple', 'Banana', 'Grapes', 'Mango']
>>> 
>>> fruits
['Apple', 'Banana', 'Grapes', 'Mango']
>>> 
>>> del fruits[1]
>>> 
>>> fruits
['Apple', 'Grapes', 'Mango']

 

Above snippet demonstrates the use of the del statement for removing an element from a list at a specified index. Here's how it works:

 

fruits = ['Apple', 'Banana', 'Grapes', 'Mango']

This line creates a list named fruits containing four elements: 'Apple', 'Banana', 'Grapes', and 'Mango'.

 

del fruits[1]

This line uses the del statement to delete the element at index 1 of the fruits list. In Python, list indices start at 0, so index 1 refers to the second element in the list, which is 'Banana'.

 

After executing del fruits[1], the list fruits is modified. The second element 'Banana' is removed, and the remaining elements after 'Banana' are shifted left by one index. Therefore, the list fruits now contains the elements ['Apple', 'Grapes', 'Mango'].

 

In summary, this snippet creates a list of fruits and then removes 'Banana' from the list, leaving the other fruits shifted accordingly in the list.

 

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment