Introduction
In this lab, you will learn how to identify if a variable is a set in Python. You'll begin by understanding the fundamental characteristics of sets, including their unordered nature and the uniqueness of their elements. Through hands-on exercises, you'll create sets using both curly braces and the set() constructor, and explore common set operations like adding and removing elements, as well as checking for membership.
The lab will then guide you through using the type() function and the isinstance() function to determine if a variable is indeed a set. By the end of this lab, you'll be equipped with the knowledge and skills to confidently identify sets in your Python code.
Understand Sets
In this step, you will learn about sets in Python. Sets are unordered collections of unique elements. This means that a set cannot contain duplicate values, and the order of elements in a set is not guaranteed. Sets are useful for performing mathematical set operations like union, intersection, and difference.
Let's start by creating a set. You can create a set using curly braces {} or the set() constructor.
Open the VS Code editor in the LabEx environment.
Create a new file named
sets_example.pyin the~/projectdirectory.## Create a set using curly braces my_set = {1, 2, 3, 4, 5} print(my_set) ## Create a set using the set() constructor another_set = set([3, 4, 5, 6, 7]) print(another_set)Run the script using the
pythoncommand in the terminal:python ~/project/sets_example.pyYou should see the following output:
{1, 2, 3, 4, 5} {3, 4, 5, 6, 7}
Now, let's explore some common set operations.
Add the following code to your
sets_example.pyfile:## Add an element to a set my_set.add(6) print(my_set) ## Remove an element from a set my_set.remove(1) print(my_set) ## Check if an element is in a set print(3 in my_set) print(1 in my_set)Run the script again:
python ~/project/sets_example.pyYou should see output similar to this:
{1, 2, 3, 4, 5, 6} {2, 3, 4, 5, 6} True False
Sets are particularly useful for removing duplicate elements from a list.
Add the following code to your
sets_example.pyfile:## Create a list with duplicate elements my_list = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] print(my_list) ## Convert the list to a set to remove duplicates unique_elements = set(my_list) print(unique_elements)Run the script:
python ~/project/sets_example.pyThe output should be:
[1, 2, 2, 3, 3, 3, 4, 4, 4, 4] {1, 2, 3, 4}
As you can see, the set unique_elements contains only the unique elements from the original list.
Use type() to Identify
In this step, you will learn how to use the type() function in Python to identify the data type of a variable. Understanding data types is crucial for writing correct and efficient code.
The type() function returns the type of an object. Let's see how it works with different data types.
Open the VS Code editor in the LabEx environment.
Create a new file named
type_example.pyin the~/projectdirectory.## Check the type of an integer x = 10 print(type(x)) ## Check the type of a float y = 3.14 print(type(y)) ## Check the type of a string z = "Hello" print(type(z)) ## Check the type of a boolean a = True print(type(a)) ## Check the type of a list b = [1, 2, 3] print(type(b)) ## Check the type of a tuple c = (1, 2, 3) print(type(c)) ## Check the type of a set d = {1, 2, 3} print(type(d)) ## Check the type of a dictionary e = {"name": "Alice", "age": 30} print(type(e))Run the script using the
pythoncommand in the terminal:python ~/project/type_example.pyYou should see the following output:
<class 'int'> <class 'float'> <class 'str'> <class 'bool'> <class 'list'> <class 'tuple'> <class 'set'> <class 'dict'>
The output shows the data type of each variable. For example, <class 'int'> indicates that the variable is an integer, and <class 'str'> indicates that the variable is a string.
Understanding the data type of a variable is important because it determines what operations you can perform on that variable. For example, you can perform arithmetic operations on integers and floats, but not on strings.
Let's see an example of how the type() function can be used to check if a variable is of a specific type before performing an operation.
Add the following code to your
type_example.pyfile:## Check if a variable is an integer before adding 5 to it num = 10 if type(num) == int: result = num + 5 print(result) else: print("Variable is not an integer") ## Check if a variable is a string before concatenating it with another string text = "Hello" if type(text) == str: greeting = text + ", World!" print(greeting) else: print("Variable is not a string")Run the script again:
python ~/project/type_example.pyYou should see the following output:
15 Hello, World!
In this example, the type() function is used to check if the variable num is an integer and the variable text is a string before performing the addition and concatenation operations, respectively.
Confirm with isinstance()
In this step, you will learn how to use the isinstance() function in Python to confirm if an object is an instance of a particular class or type. This is a more robust and recommended way to check data types compared to using type().
The isinstance() function takes two arguments: the object to check and the class or type to check against. It returns True if the object is an instance of the specified class or type, and False otherwise.
Open the VS Code editor in the LabEx environment.
Create a new file named
isinstance_example.pyin the~/projectdirectory.## Check if a variable is an integer x = 10 print(isinstance(x, int)) ## Check if a variable is a float y = 3.14 print(isinstance(y, float)) ## Check if a variable is a string z = "Hello" print(isinstance(z, str)) ## Check if a variable is a boolean a = True print(isinstance(a, bool)) ## Check if a variable is a list b = [1, 2, 3] print(isinstance(b, list)) ## Check if a variable is a tuple c = (1, 2, 3) print(isinstance(c, tuple)) ## Check if a variable is a set d = {1, 2, 3} print(isinstance(d, set)) ## Check if a variable is a dictionary e = {"name": "Alice", "age": 30} print(isinstance(e, dict))Run the script using the
pythoncommand in the terminal:python ~/project/isinstance_example.pyYou should see the following output:
True True True True True True True True
All the variables are instances of the types we checked against, so isinstance() returned True in each case.
isinstance() is particularly useful when dealing with inheritance. If a class inherits from another class, an object of the subclass is also considered an instance of the parent class.
Add the following code to your
isinstance_example.pyfile:class Animal: pass class Dog(Animal): pass my_dog = Dog() ## Check if my_dog is an instance of Dog print(isinstance(my_dog, Dog)) ## Check if my_dog is an instance of Animal print(isinstance(my_dog, Animal))Run the script again:
python ~/project/isinstance_example.pyYou should see the following output:
True True
In this example, Dog inherits from Animal. Therefore, my_dog is an instance of both Dog and Animal.
Using isinstance() is generally preferred over type() because it correctly handles inheritance and is more flexible.
Summary
In this lab, you learned about sets in Python, which are unordered collections of unique elements. You created sets using curly braces {} and the set() constructor, and performed common set operations like adding and removing elements.
Furthermore, you explored how sets can be used to remove duplicate elements from a list by converting the list to a set. You also learned how to check for membership in a set using the in operator.



