I'm trying to re-create a Solidity contract in Vyper for a demonstration and am trying to figure out the best way to replicate adding/removing from an array of structs... As far as I can tell I'd have to use a hashmap of [uint256, mystruct] and then keep track of the index with a separate variable... is that the correct way to do this? What about for removing or zeroing a struct from the hashmap?

Solidity Code:

struct MyStruct {
    string name;
    uint age;
MyStruct[] public myStructs;

uint256 structCount;

// add
myStructs.push("Alice", 22);
structCount += 1;

// remove
delete myStructs[0];
structCount -= 1;

Work-in-progress Vyper Code:

struct MyStruct:
    name: String[64]
    age: uint256

myStructs: public(HashMap[uint256, MyStruct])

structIndex: uint256
structCount: uint256

# add
self.myStructs[self.structIndex] = MyStruct({name: "Alice", age: 22})
self.structIndex += 1
self.structCount += 1

# remove
thisStruct: MyStruct = self.myStructs[0]

# is this the only way to do this?
thisStruct.name = ""
thisStruct.age = 0

self.structCount -= 1
  • Last time I checked vyper didn't have dynamic arrays. It was the language philosophy to use fixed length arrays. So you are doing exactly as expected using a mapping and some counters.
    – Ismael
    Commented Apr 28, 2021 at 4:32

1 Answer 1


Possibly someone else will chime in with Vyper suggestions but I think you might be starting out wrong-footed.

This doesn't do what I imagine you think it does:

// remove
delete myStructs[0];
structCount -= 1;

delete does not splice/re-organize the array as you might expect. If you have for example:

0: alice
1: bob
2: carol

Then, delete 0, you will have:

0: null
1: bob
2: carol

Although you decrement the count, the count is rather useless and the array hasn't become any shorter than it was before.

Implementing the remove function uses a well-established pattern that combines a mapping of keys and pointers with an array and reorganization process that is appropriate for the EVM.

See "Mapped Struct with Delete-enabled Index" over here: Are there well-solved and simple storage patterns for Solidity?

I imagine if you have the method sorted out, it should take only a modest effort to translate the steps into Vyper.

Hope it helps.

  • Yeah I should have probably been more descriptive in the example there... I understand that its not actually removing the element from the array, which is why I had the structCount variable since the array.length property can't be relied on. That posted you linked to is pretty cool though, definitely going to be useful for some other work.
    – Pathead
    Commented Apr 27, 2021 at 17:15

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.