Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

Python Sets

Uploaded by

Garuma Abdisa
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Python Sets

Uploaded by

Garuma Abdisa
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Python Sets: Overview

A set in Python is an unordered collection of unique elements. Sets are mutable, meaning you
can add or remove elements, but their elements must be immutable (e.g., integers, strings,
tuples). Sets are particularly useful for membership testing and eliminating duplicate entries.

Creating a Set

You can create a set using the set() constructor or curly braces {}.

Example:

python
Copy code
# Creating a set with curly braces
fruits = {"apple", "banana", "cherry"}
print(fruits) # Output: {'apple', 'banana', 'cherry'}

# Creating a set using the set() function


numbers = set([1, 2, 3, 3, 4])
print(numbers) # Output: {1, 2, 3, 4} # Duplicate '3' is removed

Characteristics of Sets

1. Unordered: Elements have no fixed position, so indexing is not supported.


2. Unique Elements: Duplicate elements are automatically removed.
3. Mutable: You can add or remove elements.

Common Set Operations

1. Adding Elements

Use the add() method to add a single element to a set.

python
Copy code
fruits = {"apple", "banana"}
fruits.add("cherry")
print(fruits) # Output: {'apple', 'banana', 'cherry'}

2. Updating Elements

Use the update() method to add multiple elements.

python
Copy code
fruits = {"apple", "banana"}
fruits.update(["cherry", "orange"])
print(fruits) # Output: {'apple', 'banana', 'cherry', 'orange'}
3. Removing Elements

 remove(): Removes a specific element; raises an error if the element does not exist.
 discard(): Removes a specific element; does not raise an error if the element does not
exist.
 pop(): Removes a random element.
 clear(): Empties the set.

python
Copy code
fruits = {"apple", "banana", "cherry"}
fruits.remove("banana") # Removes 'banana'
print(fruits) # Output: {'apple', 'cherry'}

fruits.discard("orange") # No error if 'orange' is absent

fruits.pop() # Removes a random element


print(fruits)

fruits.clear() # Empties the set


print(fruits) # Output: set()

4. Set Membership

Check if an element exists in a set using in or not in.

python
Copy code
fruits = {"apple", "banana", "cherry"}
print("apple" in fruits) # Output: True
print("orange" not in fruits) # Output: True

Mathematical Set Operations

1. Union

Combines elements from two sets, removing duplicates.

python
Copy code
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1.union(set2)) # Output: {1, 2, 3, 4, 5}

2. Intersection

Finds common elements between two sets.

python
Copy code
print(set1.intersection(set2)) # Output: {3}
3. Difference

Finds elements in one set that are not in the other.

python
Copy code
print(set1.difference(set2)) # Output: {1, 2}

4. Symmetric Difference

Finds elements in either of the sets but not in both.

python
Copy code
print(set1.symmetric_difference(set2)) # Output: {1, 2, 4, 5}

Set Comprehension

Like list comprehensions, sets support comprehensions for generating new sets.

Example:

python
Copy code
squared = {x ** 2 for x in range(5)}
print(squared) # Output: {0, 1, 4, 9, 16}

Practical Applications of Sets

1. Eliminating Duplicates from a List

python
Copy code
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers)
print(unique_numbers) # Output: {1, 2, 3, 4, 5}

2. Membership Testing

python
Copy code
names = {"Alice", "Bob", "Charlie"}
if "Bob" in names:
print("Bob is in the set!") # Output: Bob is in the set!

3. Set Algebra For operations like finding common employees in two departments or
differences in datasets.

Summary
 Use sets when you need to maintain unique elements and perform mathematical
operations.
 Sets are unordered and mutable but do not support indexing.
 Python provides several built-in methods to manipulate sets, making them powerful for
many use cases.

You might also like