Table of Contents
ToggleSets in Python are unordered collections of unique elements. This guide explains how to access set items using loops, list comprehensions, subsets, and membership checks.
A for loop in Python is used for iterating over a set, accessing each element sequentially.
# Defining a set
langs = {"C", "C++", "Java", "Python"}
# Accessing set items using a for loop
for lang in langs:
print(lang)
List comprehension allows converting a set into a list while iterating over its elements.
my_set = {1, 2, 3, 4, 5}
# Accessing set items using list comprehension
accessed_items = [item for item in my_set]
print(accessed_items)
A subset contains only elements that exist in another set. Python provides methods to check and generate subsets.
import itertools
# Defining a set
original_set = {1, 2, 3, 4}
# Checking if {1, 2} is a subset of the original set
is_subset = {1, 2}.issubset(original_set)
print("{1, 2} is a subset of the original set:", is_subset)
# Generating all subsets with two elements
subsets_with_two_elements = [set(subset) for subset in itertools.combinations(original_set, 2)]
print("Subsets with two elements:", subsets_with_two_elements)
You can check if an element exists in a set using the in and not in operators.
# Defining a set
langs = {"C", "C++", "Java", "Python"}
# Checking if an item exists in the set
if "Java" in langs:
print("Java is present in the set.")
# Checking if an item does not exist in the set
if "SQL" not in langs:
print("SQL is not present in the set.")
It will produce the following output −
Java is present in the set.
SQL is not present in the set.
