OKPEDIA PYTHON LISTA EN

How to remove an item from a list in Python

To delete an element from the list in the python language you can use the function del

del lista[indice]

The pop method is used to extract and delete an element from the list

lista.pop(indice)

To remove all items with a certain value from the list

lista.remove(valore)

Deleting elements from a list involves moving and changing the index number of subsequent elements. Therefore, the operation has complexity O(n).

Examples

Example 1 ( del )

Given the following list:

lista=["A","B","C","D","E","F"]

To eliminate the second element with the method del.

del lista[0]

The first element of the list has index zero, the second has index one, etc.

After the operation the list is

['B', 'C', 'D', 'E', 'F']

Now, the first element of the list is 'B'.

Example 2 ( pop )

To extract and delete the second element of the list

x=lista.pop(1)

The pop method extracts the second element of the list ('C') and assigns it to the variable x. Then remove the item from the list.

Now, the list is

['B', 'D', 'E', 'F']

Example 3 ( remove )

To delete items in the list that have the value 'E'

lista.remove('E')

Now, the list is

['B', 'D', 'F']

Example 4 ( range )

To delete the first two elements of the list:

del lista[0:2]

The function removes the elements from position 0 to position 2 excluded.

Now, the list is

['F']

There is only the F element in the list

https://how.okpedia.org/en/python/how-to-remove-an-object-from-python-list


Report us an error or send a suggestion to improve this page


Python List


FacebookTwitterLinkedinLinkedin