How can I remove an item from a repeated protobuf field in python?

22,725

Solution 1

As noted in the documentation, the object wrapping a repeated field in Protobuf behaves like a regular Python sequence. Therefore, you should be able to simply do

del foo.fields[index]

For example, to remove the last element,

del foo.fields[-1]

Solution 2

In Python, deleting an element from a list could be done in this way:

list.remove(item_to_be_removed)

or

del list[index]
Share:
22,725

Related videos on Youtube

Dereck Wonnacott
Author by

Dereck Wonnacott

Updated on April 04, 2020

Comments

  • Dereck Wonnacott
    Dereck Wonnacott about 4 years

    I have a protobuf message that contains a repeated field. I would like to remove one of the items in the list but I can't seem to find a good way to do so without copying all of the items out of the repeated field into a list, clearing the repeated field, and repopulating it.

    In C++ there is a RemoveLast() function, but this doesn't seem to appear in the python API...

  • Catskul
    Catskul over 10 years
    This is not a python list. It's a custom type. Remove is not a member.
  • George V. Reilly
    George V. Reilly about 10 years
    If you want to delete all of the repeated fields, use del foo.fields[:]
  • chase
    chase over 9 years
    @Catskul this actually works as of protobuf 2.6; they've added the pythonic list-like operations extend() and remove() to the RepeatedCompositeFieldContainer type.