How to Check If a Set Contains Only Numbers in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a set contains only numbers in Python. The lab focuses on defining numeric sets, including empty sets, sets of integers, sets of floats, and mixed sets containing both integers and floats. You will also explore how sets handle duplicate values, ensuring uniqueness.

The lab guides you through creating a Python file named numeric_sets.py, adding code to define and print various sets, and running the script to observe the output. You'll learn how to use the set() constructor and how sets automatically remove duplicate values, demonstrating the fundamental properties of sets in Python.


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(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python/BasicConceptsGroup -.-> python/numeric_types("Numeric Types") python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/DataStructuresGroup -.-> python/sets("Sets") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") python/PythonStandardLibraryGroup -.-> python/data_collections("Data Collections") subgraph Lab Skills python/numeric_types -.-> lab-559559{{"How to Check If a Set Contains Only Numbers in Python"}} python/conditional_statements -.-> lab-559559{{"How to Check If a Set Contains Only Numbers in Python"}} python/sets -.-> lab-559559{{"How to Check If a Set Contains Only Numbers in Python"}} python/build_in_functions -.-> lab-559559{{"How to Check If a Set Contains Only Numbers in Python"}} python/data_collections -.-> lab-559559{{"How to Check If a Set Contains Only Numbers in Python"}} end

Define Numeric Sets

In this step, you will learn how to define sets containing numbers in Python. Sets are unordered collections of unique elements. This means that a set cannot contain duplicate values. We will focus on creating sets of integers and floats.

First, let's create a Python file named numeric_sets.py in your ~/project directory using the VS Code editor.

## Create an empty set
empty_set = set()
print("Empty Set:", empty_set)

## Create a set of integers
integer_set = {1, 2, 3, 4, 5}
print("Integer Set:", integer_set)

## Create a set of floats
float_set = {1.0, 2.5, 3.7, 4.2, 5.9}
print("Float Set:", float_set)

## Create a mixed set (integers and floats)
mixed_set = {1, 2.0, 3, 4.5, 5}
print("Mixed Set:", mixed_set)

Save the file as numeric_sets.py in your ~/project directory. Now, run the script using the following command in the terminal:

python numeric_sets.py

You should see the following output:

Empty Set: set()
Integer Set: {1, 2, 3, 4, 5}
Float Set: {1.0, 2.5, 3.7, 4.2, 5.9}
Mixed Set: {1, 2.0, 3, 4.5, 5}

Notice that the order of elements in the set may not be the same as the order in which they were defined. This is because sets are unordered collections. Also, sets automatically remove duplicate values.

Now, let's add some more examples to your numeric_sets.py file to demonstrate the uniqueness of sets:

## Create a set with duplicate values
duplicate_set = {1, 2, 2, 3, 4, 4, 5}
print("Duplicate Set:", duplicate_set)

## Create a set from a list with duplicate values
duplicate_list = [1, 2, 2, 3, 4, 4, 5]
unique_set = set(duplicate_list)
print("Unique Set from List:", unique_set)

Save the changes and run the script again:

python numeric_sets.py

You should see the following output:

Empty Set: set()
Integer Set: {1, 2, 3, 4, 5}
Float Set: {1.0, 2.5, 3.7, 4.2, 5.9}
Mixed Set: {1, 2.0, 3, 4.5, 5}
Duplicate Set: {1, 2, 3, 4, 5}
Unique Set from List: {1, 2, 3, 4, 5}

As you can see, the duplicate_set and unique_set both contain only unique values, even though we tried to create them with duplicate values.

Use all() with isinstance()

In this step, you will learn how to use the all() function in combination with the isinstance() function to check if all elements in a set are of a specific numeric type. This is useful for validating the contents of a set before performing operations on it.

The all() function returns True if all elements in an iterable (like a set) are true. The isinstance() function checks if an object is an instance of a specified class or type.

Let's modify the numeric_sets.py file you created in the previous step to include these checks. Open numeric_sets.py in the VS Code editor and add the following code:

def check_if_all_are_integers(input_set):
  """Checks if all elements in the set are integers."""
  return all(isinstance(x, int) for x in input_set)

def check_if_all_are_floats(input_set):
  """Checks if all elements in the set are floats."""
  return all(isinstance(x, float) for x in input_set)

## Example usage:
integer_set = {1, 2, 3, 4, 5}
float_set = {1.0, 2.5, 3.7, 4.2, 5.9}
mixed_set = {1, 2.0, 3, 4.5, 5}

print("Are all elements in integer_set integers?", check_if_all_are_integers(integer_set))
print("Are all elements in float_set floats?", check_if_all_are_floats(float_set))
print("Are all elements in mixed_set integers?", check_if_all_are_integers(mixed_set))
print("Are all elements in mixed_set floats?", check_if_all_are_floats(mixed_set))

Save the file and run it using the following command:

python numeric_sets.py

You should see the following output:

Are all elements in integer_set integers? True
Are all elements in float_set floats? True
Are all elements in mixed_set integers? False
Are all elements in mixed_set floats? False

The output shows that integer_set contains only integers, float_set contains only floats, and mixed_set contains a mix of integers and floats, so the checks return False for both integer and float checks.

Now, let's add a function to check if all elements are either integers or floats (i.e., numeric):

def check_if_all_are_numeric(input_set):
  """Checks if all elements in the set are either integers or floats."""
  return all(isinstance(x, (int, float)) for x in input_set)

print("Are all elements in mixed_set numeric?", check_if_all_are_numeric(mixed_set))

string_set = {"a", "b", "c"}
print("Are all elements in string_set numeric?", check_if_all_are_numeric(string_set))

Save the file and run it again:

python numeric_sets.py

You should see the following output:

Are all elements in integer_set integers? True
Are all elements in float_set floats? True
Are all elements in mixed_set integers? False
Are all elements in mixed_set floats? False
Are all elements in mixed_set numeric? True
Are all elements in string_set numeric? False

This demonstrates how to use all() and isinstance() to validate the types of elements within a set.

Handle Empty Sets

In this step, you will learn how to handle empty sets when using the all() and isinstance() functions. Empty sets are a special case because they contain no elements. Understanding how these functions behave with empty sets is crucial for writing robust code.

Let's consider what happens when you use all() with an empty set. The all() function returns True if all elements in the iterable are true. Since an empty set has no elements, it can be argued that "all" of its elements are true, simply because there are no elements to be false.

Let's modify the numeric_sets.py file to demonstrate this. Open numeric_sets.py in the VS Code editor and add the following code:

def check_if_all_are_integers(input_set):
  """Checks if all elements in the set are integers."""
  return all(isinstance(x, int) for x in input_set)

## Example with an empty set:
empty_set = set()
print("Is empty_set all integers?", check_if_all_are_integers(empty_set))

Save the file and run it using the following command:

python numeric_sets.py

You should see the following output:

Is empty_set all integers? True

This result might seem counterintuitive at first. However, it's consistent with the definition of all().

Now, let's consider a scenario where you want to explicitly handle empty sets differently. You can add a check for an empty set before using all():

def check_if_all_are_integers_safe(input_set):
  """Checks if all elements in the set are integers, handling empty sets explicitly."""
  if not input_set:
    return False  ## Or True, depending on your desired behavior for empty sets
  return all(isinstance(x, int) for x in input_set)

empty_set = set()
print("Is empty_set all integers (safe)?", check_if_all_are_integers_safe(empty_set))

integer_set = {1, 2, 3}
print("Is integer_set all integers (safe)?", check_if_all_are_integers_safe(integer_set))

Save the file and run it again:

python numeric_sets.py

You should see the following output:

Is empty_set all integers (safe)? False
Is integer_set all integers (safe)? True

In this example, the check_if_all_are_integers_safe function returns False for an empty set. You can modify the return value in the if not input_set: block to suit your specific needs. Handling empty sets explicitly can prevent unexpected behavior in your code.

Summary

In this lab, you learned how to define sets containing numbers in Python, including empty sets, sets of integers, sets of floats, and mixed sets containing both integers and floats. You also observed that sets are unordered collections and automatically remove duplicate values.

The lab demonstrated how to create sets directly and from lists with duplicate values, highlighting the set's property of maintaining only unique elements. The examples provided a practical understanding of how sets handle different numeric types and eliminate redundancy.