1

How can I remove an object from array in python?

I want to select an msgID and want to delete that full object with username, msg, time_stamp (all of it).

room_msg =  [
 {
  'msgID': 1, 
  'username': 'User1',
  'msg': 'msg1', 
  'time_stamp': 'May-31 05:29PM'},
 {
  'msgID': 2,
  'username': 'User2', 
  'msg': 'msg2', 
  'time_stamp': 'May-31 05:29PM'},
{
  'msgID': 3, 
  'username': 'User3', 
  'msg': 'msg3', 
  'time_stamp': 'May-31 05:29PM'} ]

Like if I select 'msgID': 3 after deleting the 'msgID': 3 the array should like this

room_msg = [
 {
  'msgID': 1, 
  'username': 'User1',
  'msg': 'msg1', 
  'time_stamp': 'May-31 05:29PM'},
 {
  'msgID': 2,
  'username': 'User2', 
  'msg': 'msg2', 
  'time_stamp': 'May-31 05:29PM'}
]

Is that possible? I can't find x with that msgID room_msg[x].

3
  • FWIW: Python has lists as the basic sequence collection type, not arrays; [..] creates a list. There are many examples on how to manipulate lists - now using the right terminology, try some internet/SO searches. “python remove list item by property” (eg.) Commented May 31, 2020 at 21:51
  • any code you have tried to solve this problem. Commented May 31, 2020 at 21:51
  • Does this answer your question? Is there a simple way to delete a list element by value? Commented May 31, 2020 at 22:07

5 Answers 5

2

You can use list comprehension:

room_msg = [m for m in room_msg if m['msgID'] != 3]

from pprint import pprint
pprint(room_msg)

Prints:

[{'msg': 'msg1',
  'msgID': 1,
  'time_stamp': 'May-31 05:29PM',
  'username': 'User1'},
 {'msg': 'msg2',
  'msgID': 2,
  'time_stamp': 'May-31 05:29PM',
  'username': 'User2'}]
Sign up to request clarification or add additional context in comments.

Comments

1

This simple code should do it:

desired_id = 3  # example id

for i, msg in enumerate(room_msg):
    if msg['msgID'] == desired_id:
        del room_msg[i]

Comments

0

Try using del on the matching array indices.

for index, msg in enumerate(room_msg):
    if msg['msgID'] == 3:
        del room_msg[index]

Comments

0

This could be a way - or you use the msgID as Ident for nested - than you can erase with del room_msg[msg]

def search_and_delete(msg):
    count = 0
    for x in room_msg:
        if x['msgID'] == msg:
            room_msg.pop(count)
        count+=1

Comments

0

To delete a object from an array in python use

del arr["index"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.