Skip to content

Commit 5e8eb8a

Browse files
committed
Added list.index()
1 parent 6d0a25f commit 5e8eb8a

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

tests/snippets/list.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,12 @@
1111

1212
assert x * 0 == [], "list __mul__ by 0 failed"
1313
assert x * 2 == [1, 2, 3, 1, 2, 3], "list __mul__ by 2 failed"
14+
15+
assert ['a', 'b', 'c'].index('b') == 1
16+
assert [5, 6, 7].index(7) == 2
17+
try:
18+
['a', 'b', 'c'].index('z')
19+
except ValueError:
20+
pass
21+
else:
22+
assert False, "ValueError was not raised"

vm/src/obj/objlist.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,23 @@ pub fn list_extend(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
153153
Ok(vm.get_none())
154154
}
155155

156+
fn list_index(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
157+
trace!("list.index called with: {:?}", args);
158+
arg_check!(
159+
vm,
160+
args,
161+
required = [(list, Some(vm.ctx.list_type())), (needle, None)]
162+
);
163+
for (index, element) in get_elements(list).iter().enumerate() {
164+
let py_equal = vm.call_method(needle, "__eq__", vec![element.clone()])?;
165+
if objbool::get_value(&py_equal) {
166+
return Ok(vm.context().new_int(index.to_bigint().unwrap()));
167+
}
168+
}
169+
let needle_str = objstr::get_value(&vm.to_str(needle).unwrap());
170+
Err(vm.new_value_error(format!("'{}' is not in list", needle_str)))
171+
}
172+
156173
fn list_len(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
157174
trace!("list.len called with: {:?}", args);
158175
arg_check!(vm, args, required = [(list, Some(vm.ctx.list_type()))]);
@@ -283,6 +300,7 @@ pub fn init(context: &PyContext) {
283300
context.set_attr(&list_type, "clear", context.new_rustfunc(list_clear));
284301
context.set_attr(&list_type, "count", context.new_rustfunc(list_count));
285302
context.set_attr(&list_type, "extend", context.new_rustfunc(list_extend));
303+
context.set_attr(&list_type, "index", context.new_rustfunc(list_index));
286304
context.set_attr(&list_type, "reverse", context.new_rustfunc(list_reverse));
287305
context.set_attr(&list_type, "sort", context.new_rustfunc(list_sort));
288306
}

0 commit comments

Comments
 (0)