Skip to content

Check if List contains Item in Python

The challenge

Create a method that accepts a list and an item, and returns true if the item belongs to the list, otherwise false.

Test cases

list = [,1,2,3,5,8,13,2,2,2,11]; Test.assert_equals(include(list, 100), False, "list does not include 100") Test.assert_equals(include(list, 2), True, "list includes 2 multiple times") Test.assert_equals(include(list, 11), True, "list includes 11") Test.assert_equals(include(list, "2"), False, "list includes 2 (integer), not ''2'' (string)") Test.assert_equals(include([], ), False, "empty list doesn't include anything") Test.assert_equals(include(list, ), True, "list includes 0")
Code language: Python (python)

The solution in Python

def include(arr,item): return item in arr
Code language: Python (python)

See also  How to Convert String to Double in Python
Tags:
Subscribe
Notify of
guest
1 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
W.HatIsThis
W.HatIsThis
2 years ago

What a nice and helpful article..

1
0
Would love your thoughts, please comment.x
()
x