Skip to content

Commit e241e8c

Browse files
committed
Implemented list.count
1 parent 26c2116 commit e241e8c

2 files changed

Lines changed: 21 additions & 0 deletions

File tree

py/objlist.c

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,9 +140,23 @@ static mp_obj_t list_copy(mp_obj_t self_in) {
140140
return mp_obj_new_list(self->len, self->items);
141141
}
142142

143+
static mp_obj_t list_count(mp_obj_t self_in, mp_obj_t value) {
144+
assert(MP_OBJ_IS_TYPE(self_in, &list_type));
145+
mp_obj_list_t *self = self_in;
146+
int count = 0;
147+
for (int i = 0; i < self->len; i++) {
148+
if (mp_obj_equal(self->items[i], value)) {
149+
count++;
150+
}
151+
}
152+
153+
return mp_obj_new_int(count);
154+
}
155+
143156
static MP_DEFINE_CONST_FUN_OBJ_2(list_append_obj, mp_obj_list_append);
144157
static MP_DEFINE_CONST_FUN_OBJ_1(list_clear_obj, list_clear);
145158
static MP_DEFINE_CONST_FUN_OBJ_1(list_copy_obj, list_copy);
159+
static MP_DEFINE_CONST_FUN_OBJ_2(list_count_obj, list_count);
146160
static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(list_pop_obj, 1, 2, list_pop);
147161
static MP_DEFINE_CONST_FUN_OBJ_2(list_sort_obj, list_sort);
148162

@@ -159,6 +173,7 @@ const mp_obj_type_t list_type = {
159173
{ "append", &list_append_obj },
160174
{ "clear", &list_clear_obj },
161175
{ "copy", &list_copy_obj },
176+
{ "count", &list_count_obj },
162177
{ "pop", &list_pop_obj },
163178
{ "sort", &list_sort_obj },
164179
{ NULL, NULL }, // end-of-list sentinel

tests/basics/tests/list_count.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# list count tests
2+
a = [1, 2, 3]
3+
a = a + a + a
4+
b = [0, 0, a, 0, a, 0]
5+
print(a.count(2))
6+
print(b.count(a))

0 commit comments

Comments
 (0)