Understanding Python Sets

Sets are unordered collections of unique items in Python. They are mutable but do not allow duplicate elements. Sets are defined using curly braces {} or the set() function.

Creating Sets

Example 1: Creating a Set with Different Data Types

# Creating sets with different data types
empty_set = set()
int_set = {1, 2, 3, 4, 5}
mixed_set = {"Hello", 3.14, True, None}
print("Empty Set:", empty_set)
print("Integer Set:", int_set)
print("Mixed Set:", mixed_set)

Output

Empty Set: set()

Integer Set: {1, 2, 3, 4, 5}

Mixed Set: {False, None, 3.14, 'Hello'}

Example 2: Creating a Set from a List

# Creating a set from a list
list_data = ["Karthick AG", "Durai", "Vijay", "John", "Praveen", "Williams"]
set_from_list = set(list_data)
print("Set from List:", set_from_list)

Output

Set from List: {'Vijay', 'Praveen', 'Karthick AG', 'Durai', 'Williams', 'John'}

Explanation: Sets are created using curly braces {} or the set() function. An empty set must be created using set(), not {}, as {} creates an empty dictionary. Sets automatically remove duplicate elements and are unordered.