Book Image

Python Fundamentals

By : Ryan Marvin, Mark Nganga, Amos Omondi
Book Image

Python Fundamentals

By: Ryan Marvin, Mark Nganga, Amos Omondi

Overview of this book

After a brief history of Python and key differences between Python 2 and Python 3, you'll understand how Python has been used in applications such as YouTube and Google App Engine. As you work with the language, you'll learn about control statements, delve into controlling program flow and gradually work on more structured programs via functions. As you settle into the Python ecosystem, you'll learn about data structures and study ways to correctly store and represent information. By working through specific examples, you'll learn how Python implements object-oriented programming (OOP) concepts of abstraction, encapsulation of data, inheritance, and polymorphism. You'll be given an overview of how imports, modules, and packages work in Python, how you can handle errors to prevent apps from crashing, as well as file manipulation. By the end of this book, you'll have built up an impressive portfolio of projects and armed yourself with the skills you need to tackle Python projects in the real world.
Table of Contents (12 chapters)
Python Fundamentals
Preface

The Basics of Sets


In this section, we are going to cover sets, which are unique data structures with interesting properties.

Let's begin our journey into sets by looking at how to create sets, how to read data from them, and how to remove data from them.

Exercise 27: Creating Sets

In this exercise, we will create a set. We can do so by using the set method or the curly bracket notation:

  1. The first way to create a set is to use the set method. In Python, you can use the built-in set function to create a set. The function takes either an iterable (like a list or a tuple) or a sequence (lists, tuples, and strings are all sequences). Use the set method to define the sets named a and b, like this:

    >>> a = set([1,2,3])
    >>> a
    {1, 2, 3}
    >>> b = set((1,2,2,3,4))
    >>> b
    {1, 2, 3, 4}

    Note that in set b, all duplicated values in the original tuple were dropped.

  2. Another way is to use the curly bracket notation. Create a set directly, by using the curly bracket notation, like...