Python Tutorial (15) - Collections

Time: Column:Python views:269

Sets in Python

A set is an unordered collection of unique elements. In a set, elements are non-repetitive, and sets support common operations such as intersections, unions, and differences.

You can create a set using curly braces {}, with elements separated by commas, or by using the set() function.

Syntax:

parame = {value01, value02, ...}

or

set(value)

Example:


set1 = {1, 2, 3, 4}            # Create a set using curly braces
set2 = set([4, 5, 6, 7])        # Create a set from a list using set() function

Note: To create an empty set, you must use set() instead of {}, because {} is used to create an empty dictionary.

More Examples:

Example (Python 3.0+)

basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket)  # Shows that duplicate elements are removed
# Output: {'orange', 'banana', 'pear', 'apple'}

'orange' in basket  # Quick check for element in set
# Output: True

'crabgrass' in basket
# Output: False

# Set operations between two sets
a = set('abracadabra')
b = set('alacazam')

a  # Unique letters in a
# Output: {'a', 'r', 'b', 'c', 'd'}

a - b  # Letters in a but not in b
# Output: {'r', 'd', 'b'}

a | b  # Letters in a or b or both
# Output: {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}

a & b  # Letters in both a and b
# Output: {'a', 'c'}

a ^ b  # Letters in a or b but not both
# Output: {'r', 'd', 'b', 'm', 'z', 'l'}


Set Comprehensions:

Just like list comprehensions, set comprehensions are also supported.

Example (Python 3.0+)

a = {x for x in 'abracadabra' if x not in 'abc'}
a
# Output: {'r', 'd'}



Basic Operations on Sets

1. Adding Elements

The syntax for adding an element to a set is as follows:

s.add(x)

This adds element x to the set s. If the element is already present, no changes are made.

Example (Python 3.0+)

thisset = set(("Google", "Runoob", "Taobao"))
thisset.add("Facebook")
print(thisset)
# Output: {'Taobao', 'Facebook', 'Google', 'Runoob'}


Another method for adding elements, which can accept multiple elements as arguments, is update(). The arguments can be lists, tuples, or even dictionaries.

s.update(x)

x can contain multiple elements, separated by commas.

Example (Python 3.0+)

thisset = set(("Google", "Runoob", "Taobao"))
thisset.update({1, 3})
print(thisset)
# Output: {1, 3, 'Google', 'Taobao', 'Runoob'}

thisset.update([1, 4], [5, 6])
print(thisset)
# Output: {1, 3, 4, 5, 6, 'Google', 'Taobao', 'Runoob'}



2. Removing Elements

The syntax for removing an element from a set is:

s.remove(x)

This removes element x from the set s. If the element does not exist, an error is raised.

Example (Python 3.0+)

thisset = set(("Google", "Runoob", "Taobao"))
thisset.remove("Taobao")
print(thisset)
# Output: {'Google', 'Runoob'}

thisset.remove("Facebook")  # Raises an error because "Facebook" is not in the set
# Output: KeyError: 'Facebook'


Another method, discard(), removes an element if it exists but does not raise an error if the element is not present.

s.discard(x)

Example (Python 3.0+)

thisset = set(("Google", "Runoob", "Taobao"))
thisset.discard("Facebook")  # No error, even though "Facebook" is not in the set
print(thisset)
# Output: {'Google', 'Runoob'}


You can also randomly remove and return an element from the set using pop().

s.pop()

Script Mode Example (Python 3.0+)

thisset = set(("Google", "Runoob", "Taobao", "Facebook"))
x = thisset.pop()

print(x)
# Output: Runoob


Running the pop method multiple times will produce different results as the set is unordered. The method removes the first element from the unordered set.


3. Count the Number of Elements in a Set

The syntax for counting the number of elements in a set is as follows:

len(s)

This returns the number of elements in the set s.

Example (Python 3.0+)

thisset = set(("Google", "Runoob", "Taobao"))
print(len(thisset))
# Output: 3



4. Clear a Set

To clear all elements from a set, the following syntax is used:

s.clear()

This will remove all elements from the set s.

Example (Python 3.0+)

thisset = set(("Google", "Runoob", "Taobao"))
thisset.clear()
print(thisset)
# Output: set()

5. Check if an Element Exists in a Set

You can check whether an element exists in a set using the syntax:

x in s

This returns True if the element x is in the set s, otherwise returns False.

Example (Python 3.0+)

thisset = set(("Google", "Runoob", "Taobao"))
print("Runoob" in thisset)
# Output: True

print("Facebook" in thisset)
# Output: False



Full List of Set Methods

Below is a complete list of the built-in methods for sets:

MethodDescription
add()Adds an element to the set
clear()Removes all elements from the set
copy()Returns a shallow copy of the set
difference()Returns the difference of two or more sets (elements in one set but not in the others)
difference_update()Removes elements from the set that are present in other sets
discard()Removes a specific element from the set, if it exists
intersection()Returns the intersection of two or more sets (elements common to all sets)
intersection_update()Updates the set with the intersection of itself and another set
isdisjoint()Returns True if two sets have no elements in common
issubset()Returns True if the set is a subset of another set
issuperset()Returns True if the set is a superset of another set
pop()Removes and returns a random element from the set
remove()Removes a specific element from the set
symmetric_difference()Returns the symmetric difference of two sets (elements not in both sets)
symmetric_difference_update()Updates the set with the symmetric difference of itself and another set
union()Returns the union of two or more sets (all elements from all sets)
update()Updates the set with elements from another set or other iterables
len()Returns the number of elements in the set

This covers the essential operations for working with sets in Python. You can add, remove, and check for elements, as well as perform various set operations like unions, intersections, and differences.