Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove object from a list of objects in python

In Python, how can I remove an object from array of objects? Like this:

x = object() y = object() array = [x,y] # Remove x 

I've tried array.remove() but it only works with a value, not a specific location in the array. I need to be able to delete the object by addressing its position(remove array[0])

like image 208
user1120190 Avatar asked Mar 17 '12 23:03

user1120190


People also ask

Can you remove multiple items from a list Python?

Multiple elements can be deleted from a list in Python, based on the knowledge we have about the data. Like, we just know the values to be deleted or also know the indexes of those values.

How do I remove objects from a list?

There are three ways in which you can Remove elements from List: Using the remove() method. Using the list object's pop() method. Using the del operator.


2 Answers

In python there are no arrays, lists are used instead. There are various ways to delete an object from a list:

my_list = [1,2,4,6,7]  del my_list[1] # Removes index 1 from the list print my_list # [1,4,6,7] my_list.remove(4) # Removes the integer 4 from the list, not the index 4 print my_list # [1,6,7] my_list.pop(2) # Removes index 2 from the list 

In your case the appropriate method to use is pop, because it takes the index to be removed:

x = object() y = object() array = [x, y] array.pop(0) # Using the del statement del array[0] 
like image 59
Ricardo Murillo Avatar answered Oct 14 '22 14:10

Ricardo Murillo


del array[0] 

where 0 is the index of the object in the list (there is no array in python)

like image 39
MattoTodd Avatar answered Oct 14 '22 14:10

MattoTodd