Menu
Python Set
In Python, a set is an unordered and mutable collection of unique elements. Sets are defined by placing elements inside curly braces {} and separating them with commas. Sets automatically eliminate duplicate values.
Example:
# Creating sets
fruits_set = {"apple", "orange", "banana"}
# Adding elements to a set
fruits_set.add("grape")
# Removing elements from a set
fruits_set.remove("orange")
# Set operations
vegetables_set = {"carrot", "broccoli"}
groceries_set = fruits_set.union(vegetables_set)
In the example above, fruits_set
is a set containing unique fruit names. The add
method adds a new element ("grape") to the set, and the remove
method removes an element ("orange"). Set operations like union
combine two sets to create a new set without duplicates.