From 09669198ba618c267d68d2341cce417177eafe0e Mon Sep 17 00:00:00 2001 From: Jack Park Date: Wed, 6 Nov 2019 13:54:56 +0900 Subject: [PATCH] Implemented .pop() method for list --- py/list.go | 16 ++++++++++++++++ py/tests/list.py | 7 +++++++ 2 files changed, 23 insertions(+) diff --git a/py/list.go b/py/list.go index eee7bf3e..267ab69d 100644 --- a/py/list.go +++ b/py/list.go @@ -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 { diff --git a/py/tests/list.py b/py/tests/list.py index b832b3df..30dd69fc 100644 --- a/py/tests/list.py +++ b/py/tests/list.py @@ -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 +assert repr(a) == "[2, 3]" +assertRaises(IndexError, lambda: [].pop()) + doc="mul" a = [1, 2, 3] assert a * 2 == [1, 2, 3, 1, 2, 3]