Skip to content

Implemented .pop() method for list #126

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions py/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,22 @@ func init() {
return NoneType{}, nil
}, 0, "append(item)")

ListType.Dict["pop"] = MustNewMethod("pop", func(self Object, args Tuple) (Object, error) {
var index Object = Int(0)
listSelf := self.(*List)
err := UnpackTuple(args, nil, "pop", 0, 1, &index)
if err != nil {
return nil, err
}
i, err := IndexIntCheck(index, listSelf.Len())
if err != nil {
return nil, err
}
popElement := listSelf.Items[i]
listSelf.Items = append(listSelf.Items[:i], listSelf.Items[i+1:]...)
return popElement, nil
}, 0, "pop(index)")

ListType.Dict["extend"] = MustNewMethod("extend", func(self Object, args Tuple) (Object, error) {
listSelf := self.(*List)
if len(args) != 1 {
Expand Down
7 changes: 7 additions & 0 deletions py/tests/list.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,13 @@
assert repr(a) == "['a', 'b', 'c', 'd', 'e', 'f']"
assertRaises(TypeError, lambda: [].append())

doc="pop"
a = [1,2,3,4]
assert a.pop() == 1
assert a.pop(2) == 4
Comment on lines +40 to +41
Copy link

@ghost ghost Dec 1, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The pop operation removes and returns from the back, I think your idea was removing from the front.
It would be good if you create a new list for each test and compare your test against a list like assert a.pop(-1) == element; assert a = [...], that makes it more clear here.

Additionally the following tests would be good:

  • negative index
  • index out of range for non-empty list
  • parameter of wrong type (non-int)

assert repr(a) == "[2, 3]"
assertRaises(IndexError, lambda: [].pop())

doc="mul"
a = [1, 2, 3]
assert a * 2 == [1, 2, 3, 1, 2, 3]
Expand Down