Home Tutorials Tutorial on Membership Operators in MicroPython

Tutorial on Membership Operators in MicroPython

by shedboy71

In MicroPython, membership operators are used to test if a value or object is present in a sequence, such as a list, tuple, string, dictionary, or other iterable. These operators help you determine the presence or absence of elements within a container, which is often useful in control flow structures like if statements.

This tutorial will guide you through the use of membership operators in MicroPython, complete with examples to demonstrate their functionality.

Table of Contents:

1. Overview of Membership Operators

MicroPython supports two membership operators:

Operator Description Example
in Returns True if the specified value is found in the sequence a in b
not in Returns True if the specified value is not found in the sequence a not in b

These operators are commonly used to check the presence of elements in collections such as lists, tuples, strings, and dictionaries.

2. in Operator

The in operator checks if a specified value exists within a sequence. It returns True if the value is present and False otherwise.

Syntax:

result = element in sequence

Example: Using in with a List

numbers = [1, 2, 3, 4, 5]

# Check if 3 is in the list
result = 3 in numbers
print(result)  # Output: True

Explanation:

The in operator checks if 3 exists in the numbers list. Since it is present, it returns True.

3. not in Operator

The not in operator checks if a specified value does not exist within a sequence. It returns True if the value is not present and False otherwise.

Syntax:

result = element not in sequence

Example: Using not in with a List

numbers = [1, 2, 3, 4, 5]

# Check if 6 is not in the list
result = 6 not in numbers
print(result)  # Output: True

Explanation:

The not in operator checks if 6 does not exist in the numbers list. Since it is not present, it returns True.

4. Using Membership Operators with Different Data Types

Example 1: Using in and not in with Strings

Strings are sequences of characters, so you can use membership operators to check for substrings.

text = "Hello, MicroPython!"

# Check if a substring is in the string
result = "Micro" in text
print(result)  # Output: True

# Check if a substring is not in the string
result = "Python" not in text
print(result)  # Output: False

Explanation:

“Micro” in text returns True because “Micro” is a substring of the text variable.
“Python” not in text returns False because “Python” is part of the string.

Example 2: Using in with Tuples

You can use membership operators to check for the presence of an element in a tuple.

my_tuple = (10, 20, 30, 40)

# Check if 20 is in the tuple
result = 20 in my_tuple
print(result)  # Output: True

Example 3: Using in with Dictionaries

When used with dictionaries, the in and not in operators check for the presence of keys, not values.

my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}

# Check if a key is in the dictionary
result = 'name' in my_dict
print(result)  # Output: True

# Check if a key is not in the dictionary
result = 'address' not in my_dict
print(result)  # Output: True

Explanation:

‘name’ in my_dict checks if the dictionary contains the key ‘name’.
‘address’ not in my_dict checks if the dictionary does not contain the key ‘address’.

Example 4: Using in with Lists of Lists

You can use membership operators with nested lists to check for the presence of sublists.

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Check if a sublist is in the nested list
result = [4, 5, 6] in nested_list
print(result)  # Output: True

5. Practical Examples

Example 1: Checking User Input

Use membership operators to check if the user’s input is among a list of valid options.

valid_options = ['start', 'stop', 'pause']

user_input = 'start'

# Check if the input is a valid option
if user_input in valid_options:
    print("Valid command!")
else:
    print("Invalid command.")

Output:

Valid command!

Explanation:

The in operator checks if user_input is one of the items in the valid_options list.

Example 2: Filtering Items in a List

Use membership operators to filter out unwanted elements from a list.

numbers = [1, 2, 3, 4, 5, 6]
exclude = [2, 4, 6]

# Create a new list that excludes certain numbers
filtered_numbers = [num for num in numbers if num not in exclude]
print(filtered_numbers)  # Output: [1, 3, 5]

Explanation:

The list comprehension uses the not in operator to include only the numbers that are not in the exclude list.

Example 3: Searching for Keys in a Dictionary

person = {'name': 'John', 'age': 25, 'country': 'USA'}

# Check if a key exists in the dictionary before accessing it
if 'age' in person:
    print(f"Age: {person['age']}")
else:
    print("Age key is not found.")

Output:

Age: 25

Explanation:

Before trying to access the ‘age’ key in the dictionary, the code uses the in operator to ensure it exists.

Conclusion

Membership operators (in and not in) are versatile tools in MicroPython that allow you to check if an element exists within various sequences such as lists, tuples, strings, and dictionaries.

They help you write more flexible and robust code by making it easy to validate input, search for elements, and filter collections.

in: Returns True if the specified element exists in the sequence.
not in: Returns True if the specified element does not exist in the sequence.

With these operators, you can efficiently perform checks and conditions on a wide range of data structures, enhancing the decision-making logic in your MicroPython programs.se operators, you can efficiently perform checks and conditions on a wide range of data structures, enhancing the decision-making logic in your MicroPython programs.

You may also like

Leave a Comment