Python Set Tutorial with Examples

Introduction

Sets in Python are unordered collections of unique items. They are mutable, meaning that their contents can be changed after creation, but they do not allow duplicate elements. Sets are commonly used for membership testing and eliminating duplicate entries.

Table of Contents

  1. Define Set and Key Points
  2. Create Set
  3. Add Set Items
  4. Access Set Items
  5. Remove Set Items
  6. Loop Sets
  7. Set Comprehension
  8. Set Operations
  9. Frozen Sets
  10. Set Methods
  11. Conclusion

Set Overview

A set is a collection of unordered, unique items. Sets are:

  • Unordered: Items have no index or order.
  • Mutable: You can add or remove items.
  • Unique: Duplicate items are not allowed.

1. Create Set

Sets are created by placing items inside curly braces {}, separated by commas, or by using the set() function.

Example

# Creating a set using curly braces
my_set = {1, 2, 3, "hello", 4.5}
print(my_set)  # Output: {1, 2, 3, 4.5, 'hello'}

# Creating a set using the set() function
my_set = set([1, 2, 3, "hello", 4.5])
print(my_set)  # Output: {1, 2, 3, 4.5, 'hello'}

2. Add Set Items

Items can be added to a set using the add() method for single items and the update() method for multiple items.

Example

# Using add() to add a single item
my_set.add("world")
print(my_set)  # Output: {1, 2, 3, 4.5, 'hello', 'world'}

# Using update() to add multiple items
my_set.update([5, 6, 7])
print(my_set)  # Output: {1, 2, 3, 4.5, 5, 6, 7, 'hello', 'world'}

3. Access Set Items

Since sets are unordered, you cannot access items using an index. However, you can loop through the set to access its items.

Example

# Looping through a set
for item in my_set:
    print(item)

4. Remove Set Items

Items can be removed from a set using the remove(), discard(), pop(), and clear() methods.

Example

# Using remove() to remove a specific item
my_set.remove("hello")
print(my_set)  # Output: {1, 2, 3, 4.5, 5, 6, 7, 'world'}

# Using discard() to remove a specific item (does not raise an error if item is not found)
my_set.discard("world")
print(my_set)  # Output: {1, 2, 3, 4.5, 5, 6, 7}

# Using pop() to remove and return an arbitrary item
popped_item = my_set.pop()
print(popped_item)  # Output: (an arbitrary item)
print(my_set)  # Output: (remaining items)

# Using clear() to remove all items
my_set.clear()
print(my_set)  # Output: set()

5. Loop Sets

You can loop through the items in a set using a for loop.

Example

# Creating a set
fruits = {"apple", "banana", "cherry"}

# Looping through a set
for fruit in fruits:
    print(fruit)

# Output:
# apple
# banana
# cherry

6. Set Comprehension

Set comprehension provides a concise way to create sets.

Example

# Using set comprehension to create a set of squares
squares = {x**2 for x in range(10)}
print(squares)  # Output: {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}

7. Set Operations

Sets support various operations like union, intersection, difference, and symmetric difference.

Example

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

# Union of sets
union_set = set1.union(set2)
print(union_set)  # Output: {1, 2, 3, 4, 5, 6}

# Intersection of sets
intersection_set = set1.intersection(set2)
print(intersection_set)  # Output: {3, 4}

# Difference of sets
difference_set = set1.difference(set2)
print(difference_set)  # Output: {1, 2}

# Symmetric difference of sets
symmetric_difference_set = set1.symmetric_difference(set2)
print(symmetric_difference_set)  # Output: {1, 2, 5, 6}

8. Frozen Sets

Frozen sets are immutable versions of sets. Once created, you cannot modify the items in a frozen set.

Example

# Creating a frozen set
my_frozenset = frozenset([1, 2, 3, "hello"])
print(my_frozenset)  # Output: frozenset({1, 2, 3, 'hello'})

# Frozen sets do not support add or remove operations
# my_frozenset.add("world")  # This will raise an error

9. Set Methods

Python sets have several built-in methods, including add(), remove(), discard(), pop(), clear(), union(), intersection(), difference(), symmetric_difference(), and update().

Example

# Using various set methods
example_set = {1, 2, 3, 4, 5}

# Adding an item
example_set.add(6)
print(example_set)  # Output: {1, 2, 3, 4, 5, 6}

# Removing an item
example_set.remove(2)
print(example_set)  # Output: {1, 3, 4, 5, 6}

# Using union method
set_a = {1, 2, 3}
set_b = {3, 4, 5}
union_set = set_a.union(set_b)
print(union_set)  # Output: {1, 2, 3, 4, 5}

# Using intersection method
intersection_set = set_a.intersection(set_b)
print(intersection_set)  # Output: {3}

Conclusion

Python sets are powerful and versatile data structures that allow you to store and manipulate collections of unique items. Understanding how to create, add, access, remove, and perform operations on sets is essential for effective programming in Python. This tutorial covered various aspects of sets, including creating, adding, accessing, changing, and removing items, as well as advanced topics like set comprehension, set operations, and frozen sets. By mastering these concepts, you can efficiently work with sets in your Python programs.

Comments