17
An Introduction To Software Development Using Python Spring Semester, 2015 Class #21: Sets

An Introduction To Python - Sets

Embed Size (px)

Citation preview

An Introduction To Software Development Using Python

Spring Semester, 2015

Class #21:Sets

What Is A Set?

• A set is a container that stores a collection of unique values.

• Unlike a list, the elements or members of the set are not stored in any particular order and cannot be accessed by position.

• The operations available for use with a set are the same as the operations performed on sets in mathematics.

• Because sets need not maintain a particular order, set operations are much faster than the equivalent list operations

Image Credit: woodridgehomestead.com

An Example Of SetsCheese Pizza Pepperoni Pizza Meat Lover’s Pizza

• Marinara sauce

• Pepperoni

• Italian sausage

• Slow-roasted ham

• Hardwood smoked bacon

• Seasoned pork and beef

• Marinara sauce

• Cheese

• Pepperoni

• Creamy garlic Parmesan sauce

• Cheese

• Toasted Parmesan

Image Credit: https://order.pizzahut.com/site/menu/pizza

Creating & Using Sets

• To create a set with initial elements, you can specify the elements enclosed in braces,just like in mathematics:

cheesePizza = {“Creamy Garlic Parmesan Sauce”, “Cheese”, “Toasted Parmesan”}

Image Credit: https://order.pizzahut.com/site/menu/pizza

Creating & Using Sets

• Alternatively, you can use the set function to convert any list into a set:

cheesePie = [“Creamy garlic Parmesan sauce”, “Cheese”, “Toasted Parmesan”]

cheesePizza = set(cheesePie)

Image Credit: www.clker.com

Creating & Using Sets

• For historical reasons, you cannot use {} to make an empty set in Python.

• Instead, use the set function with no arguments: cheesePizza = set()

• As with any container, you can use the len function to obtain the number of elements in a set: numberOfIngredients = len(cheesePizza)

Image Credit: freeclipartstore.com

Is Something In A Set?• To determine whether an element is contained in the set, use

the in operator or its inverse, the not in operator:

if "Toasted Parmesan" in cheesePizza : print(“A cheese pizza contains Toasted Parmesan")else : print(“A cheese pizza does not contain Toasted Parmesan")

Image Credit: www.clipartpanda.com

Sets & Order• Because sets are unordered, you cannot access the elements of a set by position

as you can with a list.

• Instead, use a for loop to iterate over the individual elements: print("The ingredients in a cheese pizza are:") for ingredient in cheesePizza : print(ingredient)

• Note that the order in which the elements of the set are visited depends on how they are stored internally. For example, the loop above displays the following: The ingredients in a Cheese pizza are: Toasted Parmesan Creamy garlic Parmesan sauce Cheese

• Note that the order of the elements in the output can be different from the order in which the set was created.

Image Credit: www.pinterest.com

Sets & Order

• The fact that sets do not retain the initial ordering is not a problem when working with sets. In fact, the lack of an ordering makes it possible to implement set operations very efficiently.

• However, you usually want to display the elements in sorted order. Use the sorted function, which returns a list (not a set) of the elements in sorted order. The following loop prints the pizza ingredients in alphabetical sorted order:

for ingredient in sorted(cheesePizza) : print(ingredient)

Image Credit: www.itweb.co.za

Adding Elements To A Set

• Like lists, sets are collections, so you can add and remove elements.

• For example, suppose we need to add more ingredient to a meat lover’s pizza. Use the add method to add elements: meatLoversPizza.add("Mushrooms")

• A set cannot contain duplicate elements. If you attempt to add an element that is already in the set, there is no effect and the set is not changed.

Image Creditwww.clipartpanda.com

Removing Elements From

A Set• There are two methods that can be used to remove individual

elements from a set. The discard method removes an element if the element exists: meatLoversPizza.discard("Italian sausage")

• The remove method, on the other hand, removes an element if it exists, but raises an exception if the given element is not a member of the set. meatLoversPizza.remove("Italian sausage")

• Finally, the clear method removes all elements of a set, leaving the empty set: meatLoversPizza.clear() # no ingredients

Image Credit: www.clker.com

Subsets• A set is a subset of another set if and only if every element of the first set

is also an element of the second set.

• The issubset method returns True or False to report whether one set is a subset of another

Cheese Pizza Pepperoni Pizza

• Marinara sauce

• Cheese

• Pepperoni

• Marinara sauce

• Cheese

Image Credit: www.vectorious.net

cheesePizza.issubset(pepperoniPizza)

Comparing Subsets

• You can also test for equality between two sets using the == and != operators.

• Two sets are equal if and only if they have exactly the same elements.

cheesePizza != pepperoniPizza

cheesePizza1 == cheesePizza2

Set Union, Intersection, and Difference

• The union of two sets contains all of the elements from both sets, with duplicates removed.

• The intersection of two sets contains all of the elements that are in both sets.

• The difference of two sets results in a new set that contains those elements in the first set that are not in the second set.

Image Credit: www.abcteach.com

cheesePizza.union(pepperoniPizza) = {“Marinara sauce”, “Cheese”, “Pepperoni”}

cheesePizza.intersection(pepperoniPizza) = {“Marinara sauce”, “Cheese”}

cheesePizza.difference(pepperoniPizza) = {“Pepperoni”}

What’s In Your Python Toolbox?

print() math strings I/O IF/Else elif While For

Lists And/Or/Not Functions Files Exception Sets

What We Covered Today

1. Sets

2. Sets & Order

3. Adding to a set

4. Removing from a set

5. Subsets

6. Union, Intersection, Difference

Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/

What We’ll Be Covering Next Time

1. Dictionaries

Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/