Skip to content

Commit 84a1729

Browse files
committed
Implemented .pop() method for list
1 parent 0c23b14 commit 84a1729

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

py/list.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,22 @@ func init() {
2828
return NoneType{}, nil
2929
}, 0, "append(item)")
3030

31+
ListType.Dict["pop"] = MustNewMethod("pop", func(self Object, args Tuple) (Object, error) {
32+
var index Object = Int(0)
33+
listSelf := self.(*List)
34+
err := UnpackTuple(args, nil, "pop", 0, 1, &index)
35+
if err != nil {
36+
return nil, err
37+
}
38+
i, err := IndexIntCheck(index, listSelf.Len())
39+
if err != nil {
40+
return nil, err
41+
}
42+
popElement := listSelf.Items[i]
43+
listSelf.Items = append(listSelf.Items[:i], listSelf.Items[i+1:]...)
44+
return popElement, nil
45+
}, 0, "pop(index)")
46+
3147
ListType.Dict["extend"] = MustNewMethod("extend", func(self Object, args Tuple) (Object, error) {
3248
listSelf := self.(*List)
3349
if len(args) != 1 {

py/tests/list.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,13 @@
3535
assert repr(a) == "['a', 'b', 'c', 'd', 'e', 'f']"
3636
assertRaises(TypeError, lambda: [].append())
3737

38+
doc="pop"
39+
a = [1,2,3,4]
40+
assert a.pop() == 1
41+
assert a.pop(2) == 4
42+
assert repr(a) == "[2, 3]"
43+
assertRaises(IndexError, lambda: [].pop())
44+
3845
doc="mul"
3946
a = [1, 2, 3]
4047
assert a * 2 == [1, 2, 3, 1, 2, 3]

0 commit comments

Comments
 (0)