Introduction
Sets are used to store unique items and to quickly check if something is in a group. They help remove duplicates and make some tasks faster.
Jump into concepts and practice - no test required
Sets are used to store unique items and to quickly check if something is in a group. They help remove duplicates and make some tasks faster.
my_set = {item1, item2, item3}
# or
my_set = set([item1, item2, item3])Sets use curly braces {} or the set() function to create.
Items in a set are unique and unordered.
fruits = {'apple', 'banana', 'orange'}numbers = set([1, 2, 2, 3, 4]) print(numbers)
a = {1, 2, 3}
b = {2, 3, 4}
common = a & b
print(common)This program shows how sets remove duplicates, check membership, and perform union, intersection, and difference operations.
items = ['apple', 'banana', 'apple', 'orange', 'banana'] unique_items = set(items) print('Unique items:', unique_items) if 'apple' in unique_items: print('Apple is in the set') set_a = {1, 2, 3} set_b = {3, 4, 5} print('Union:', set_a | set_b) print('Intersection:', set_a & set_b) print('Difference:', set_a - set_b)
Sets do not keep the order of items like lists do.
You cannot have mutable items like lists inside a set.
Sets are very fast for checking if an item exists.
Sets store unique items only.
They help remove duplicates easily.
Sets support fast membership tests and set operations like union and intersection.
set in Python?my_list = [1, 2, 2, 3, 4, 4, 4] my_set = set(my_list) print(my_set)
my_set = {1, 2, 2, 3}
print(my_set)list1 = [1, 2, 3, 4] list2 = [3, 4, 5, 6]
& operator on sets returns elements common to both sets.