Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
The Python Workshop Second Edition

You're reading from   The Python Workshop Second Edition Write Python code to solve challenging real-world problems

Arrow left icon
Product type Paperback
Published in Nov 2022
Publisher Packt
ISBN-13 9781804610619
Length 600 pages
Edition 2nd Edition
Languages
Arrow right icon
Authors (5):
Arrow left icon
Mario Corchero Jiménez Mario Corchero Jiménez
Author Profile Icon Mario Corchero Jiménez
Mario Corchero Jiménez
Andrew Bird Andrew Bird
Author Profile Icon Andrew Bird
Andrew Bird
Corey Wade Corey Wade
Author Profile Icon Corey Wade
Corey Wade
Graham Lee Graham Lee
Author Profile Icon Graham Lee
Graham Lee
Dr. Lau Cher Han Dr. Lau Cher Han
Author Profile Icon Dr. Lau Cher Han
Dr. Lau Cher Han
+1 more Show less
Arrow right icon
View More author details
Toc

Table of Contents (16) Chapters Close

Preface 1. Chapter 1: Python Fundamentals – Math, Strings, Conditionals, and Loops 2. Chapter 2: Python Data Structures FREE CHAPTER 3. Chapter 3: Executing Python – Programs, Algorithms, and Functions 4. Chapter 4: Extending Python, Files, Errors, and Graphs 5. Chapter 5: Constructing Python – Classes and Methods 6. Chapter 6: The Standard Library 7. Chapter 7: Becoming Pythonic 8. Chapter 8: Software Development 9. Chapter 9: Practical Python – Advanced Topics 10. Chapter 10: Data Analytics with pandas and NumPy 11. Chapter 11: Machine Learning 12. Chapter 12: Deep Learning with Python 13. Chapter 13: The Evolution of Python – Discovering New Python Features 14. Index 15. Other Books You May Enjoy

A survey of sets

So far, in this chapter, we have covered lists, dictionaries, and tuples. Now, let’s look at sets, which are another type of Python data structure.

Sets are a relatively new addition to the Python collection type. They are unordered collections of unique and immutable objects that support operations mimicking mathematical set theory. Since sets do not allow multiple occurrences of the same element, they can be used to effectively prevent duplicate values.

A set is a collection of objects (called members or elements). For instance, you can define set A as containing even numbers between 1 to 10, and it will contain {2,4,6,8,10}; set B can contain odd numbers between 1 to 10, and it will contain {1,3,5,7,9}.

The following figure shows a visual of two sets without overlapping values:

Figure 2.19 – Set A and Set B – each set contains a unique, distinct value

Figure 2.19 – Set A and Set B – each set contains a unique, distinct value

In the following exercise, you will work with sets in Python.

Exercise 33 – using sets in Python

In this exercise, you will practice working with sets in Python:

  1. Open a Jupyter notebook.
  2. Initialize a set using the following code. You can pass in a list to initialize a set or use curly brackets, as follows:
    s1 = set([1,2,3,4,5,6])
    print(s1)
    s2 = {1,2,2,3,4,4,5,6,6}
    print(s2)
    s3 = {3,4,5,6,6,6,1,1,2}
    print(s3)

The output is as follows:

{1, 2, 3, 4, 5, 6}
{1, 2, 3, 4, 5, 6}
{1, 2, 3, 4, 5, 6}

Here, you can see that the set is unique and unordered, so duplicate items and the original order are not preserved.

  1. Enter the following code in a new cell:
    s4 = {'martha graham, 'alivin ailey, 'isadora duncan'}
    print(s4)

You can also initialize a set using curly brackets directly.

The output is as follows:

{'martha graham', 'alvin ailey', 'isadora duncan'}
  1. Sets are mutable. Type the following code, which shows how to add a new item, pineapple, to an existing set, s4:
    s4.add('katherine dunham')
    print(s4)

The output is as follows:

{'martha graham', 'alvin ailey', 'isadora duncan'}

In this exercise, you were introduced to sets in Python. In the next section, you will dive in a bit deeper and understand the different set operations that Python offers.

Set operations

Sets support common operations such as unions and intersections. A union operation returns a single set that contains all the unique elements in both sets A and B; an intersect operation returns a single set that contains unique elements that belong to set A and also belong to set B at the same time. Let’s look at the union operation in the following figure:

Figure 2.20 – Set A in union with Set B

Figure 2.20 – Set A in union with Set B

The following figure represents the intersect operation:

Figure 2.21 – Set A intersects with Set B

Figure 2.21 – Set A intersects with Set B

Now, let’s implement these set operations in Python in the following exercise.

Exercise 34 – implementing set operations

In this exercise, we will be implementing and working with set operations:

  1. Open a new Jupyter notebook.
  2. In a new cell, type the following code to initialize two new sets:
    s5 = {1,2,3,4}
    s6 = {3,4,5,6}
  3. Use the | operator or the union method for a union operation:
    print(s5 | s6)
    print(s5.union(s6))

The output is as follows:

{1, 2, 3, 4, 5, 6}
{1, 2, 3, 4, 5, 6}
  1. Now, use the & operator or the intersection method for an intersection operation:
    print(s5 & s6)
    print(s5.intersection(s6))

The output is as follows:

{3, 4}
{3, 4}
  1. Use the operator or the difference method to find the difference between two sets:
    print(s5 - s6)
    print(s5.difference(s6))

The output is as follows:

{1, 2}
{1, 2}
  1. Now, enter the <= operator or the issubset method to check if one set is a subset of another:
    print(s5 <= s6)
    print(s5.issubset(s6))
    s7 = {1,2,3}
    s8 = {1,2,3,4,5}
    print(s7 <= s8)
    print(s7.issubset(s8))

The output is as follows:

False
False
True
True

The first two statements will return false because s5 is not a subset of s6. The last two statements will return True because s5 is a subset of s6. Note that the <= operator is a test for the subset. A proper subset is the same as a general subset, except that the sets cannot be identical. You can try it out in a new cell with the following code.

  1. Check whether s7 is a formal subset of s8, and check whether a set can be a proper subset of itself by entering the following code:
    print(s7 < s8)
    s9 = {1,2,3}
    s10 = {1,2,3}
    print(s9 < s10)
    print(s9 < s9)

The output is as follows:

True
False
False

Here, we can see that s7 is a proper subset of s8 because there are other elements in s8 apart from all the elements of s7. However, s9 is not a subset of s10 because they are identical. Therefore, a set is not a proper subset of itself.

  1. Now, use the >= operator or the issuperset method to check whether one set is the superset of another. Try this using the following code in another cell:
    print(s8 >= s7)
    print(s8.issuperset(s7))
    print(s8 > s7)
    print(s8 > s8)

The output is as follows:

True
True
True
False

The first three statements will return True because s8 is the superset of s7 and is also a proper superset of s7. The last statement will return false because no set can be a proper superset of itself.

Having completed this exercise, you now know that Python sets are useful for efficiently preventing duplicate values and are suitable for common math operations such as unions and intersections.

Note

After all the topics covered so far, you may think that sets are similar to lists or dictionaries. However, sets are unordered and do not map keys to values, so they are neither a sequence nor a mapping type; they are a type by themselves.

You have been reading a chapter from
The Python Workshop Second Edition - Second Edition
Published in: Nov 2022
Publisher: Packt
ISBN-13: 9781804610619
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image