Check if a country code is in a list of approved countries.

← Collections and Data Structures · Ref: Q1159

Use the contains operator on a List:

  if approved contains countryCode
    stdout.println("Approved")

The 'contains' operator checks whether a value exists in a List or Dict. For List, it checks element membership. For Dict, it checks key existence. See Q45 for List basics. See Q129 for Dict contains.

Example

defines module qa.collections.listcontains

  defines program

    ListContainsDemo()
      stdout <- Stdout()

      approved <- ["GB", "US", "DE", "FR", "JP"]

      // Check membership with contains operator
      countryCode <- "GB"
      if approved contains countryCode
        stdout.println(`${countryCode} is approved`)

      // Check a code that is not in the list
      unknownCode <- "ZZ"
      if not (approved contains unknownCode)
        stdout.println(`${unknownCode} is not approved`)

      // Check multiple codes
      candidates <- ["US", "BR", "FR", "CN"]
      for candidate in candidates
        if approved contains candidate
          stdout.println(`${candidate}: approved`)
        else
          stdout.println(`${candidate}: rejected`)

Common mistakes

E07620 — 'contains' on a List of String is not defined for an Integer operand — the argument must match the element type. See ek9 -h E07620 for details.

Incorrect:

if approved contains 42

Correct:

if approved contains countryCode
Other ways to ask this
  • Write code to check list membership in EK9
  • I have a list of valid codes and need to verify a value is in that list
  • Given a list of approved strings, determine if a candidate is present
  • In Java I'd use list.contains(). Write the EK9 equivalent

Coming from another language?

Java: list.contains(item). Python: item in list. Rust: vec.contains(&item). Go: manual loop (no built-in). JavaScript: array.includes(item). EK9: list contains item — operator syntax, not method call.

Keywords: approved, membership, in, list, contains, collection, lookup, check