Check List Membership

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this challenge, you will write a function to check if any element in a given list is included in another given list.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") subgraph Lab Skills python/comments -.-> lab-13657{{"`Check List Membership`"}} python/booleans -.-> lab-13657{{"`Check List Membership`"}} python/conditional_statements -.-> lab-13657{{"`Check List Membership`"}} python/for_loops -.-> lab-13657{{"`Check List Membership`"}} python/lists -.-> lab-13657{{"`Check List Membership`"}} python/tuples -.-> lab-13657{{"`Check List Membership`"}} python/function_definition -.-> lab-13657{{"`Check List Membership`"}} end

Check if any value in a list is included in another list

Write a function includes_any(lst, values) that takes in two lists as arguments. The function should check if any element in values is included in lst. If any one value is found, the function should return True, otherwise, it should return False.

To solve this problem, you can use a for loop to iterate through each value in values. Then, you can use the in operator to check if the value is included in lst. If a value is found, return True. If no value is found, return False.

def includes_any(lst, values):
  for v in values:
    if v in lst:
      return True
  return False
includes_any([1, 2, 3, 4], [2, 9]) ## True
includes_any([1, 2, 3, 4], [8, 9]) ## False

Summary

In this challenge, you learned how to check if any element in a given list is included in another given list. You used a for loop to iterate through each value in values and the in operator to check if the value is included in lst. You then returned True if any one value was found, and False otherwise.

Other Python Tutorials you may like