Python

Python Menu

Sets are lists with no duplicate entries. Let's say you want to collect a list of words used in a paragraph. This will print out a list containing "my", "name", "is", "Eric", and finally "and". Since the rest of the sentence uses words which are already in the set, they are not inserted twice:

print(set("my name is Eric and Eric is my name".split()))

Sets are a powerful tool in Python since they have the ability to calculate differences and intersections between other sets. For example, say you have a list of participants in events A and B:

a = set(["Jeff", "Mark", "Alex"])
print(a)
b = set(["John", "Alex"])
print(b)

To find out which members attended both events, you may use the "intersection" method:

a = set(["Jeff", "Mark", "Alex"]) b = set(["John", "Alex"]) print(a.intersection(b)) print(b.intersection(a))

To find out which members attended only one of the events, use the symmetric_difference method:

a = set(["Jeff", "Mark", "Alex"]) b = set(["John", "Alex"]) print(a.symmetric_difference(b)) print(b.symmetric_difference(a))

To find out which members attended only one event and not the other, use the difference method:

a = set(["Jeff", "Mark", "Alex"]) b = set(["John", "Alex"]) print(a.difference(b)) print(b.difference(a))

To receive a list of all participants, use the union method:

a = set(["Jeff", "Mark", "Alex"]) b = set(["John", "Alex"]) print(a.union(b))

Exercise

Use the given lists to print out a set containing all the participants from event A which did not attend event B.

a = ["Michael", "John", "Marie", "Cindy"] b = ["John", "Jack", "Rowel"] a = ["Michael", "John", "Marie", "Cindy"] b = ["John", "Jack", "Rowel"]
A = set(a) B = set(b)
print(A.difference(B))
test_output_contains("{'Cindy', 'Marie', 'Michael'}") success_msg("Excellent!")

Introduction

Python Basics

Python Advance

Data Science Python Tutorials

Python Functions and Methods