0
0
Pythonprogramming~5 mins

Set creation in Python

Choose your learning style9 modes available
Introduction
Sets help you store unique items without any order. They are useful when you want to avoid duplicates.
You want to keep a list of unique friends' names.
You need to remove repeated numbers from a list.
You want to check if an item is in a group quickly.
You want to combine two groups but keep only unique items.
Syntax
Python
my_set = {item1, item2, item3}
# or
my_set = set([item1, item2, item3])
Use curly braces {} to create a set with items inside.
Use set() function to create a set from other collections like lists.
Examples
Create a set of fruits using curly braces.
Python
fruits = {'apple', 'banana', 'cherry'}
Create a set from a list of numbers using the set() function.
Python
numbers = set([1, 2, 3, 4])
Create an empty set using set(), because {} creates an empty dictionary.
Python
empty_set = set()
Sample Program
This program creates a set with some fruits, including a duplicate 'apple'. It prints the set showing only unique items. Then it creates and prints an empty set.
Python
fruits = {'apple', 'banana', 'apple', 'cherry'}
print(fruits)

empty_set = set()
print(empty_set)
OutputSuccess
Important Notes
Sets do not keep the order of items, so the printed order may vary.
Duplicates are automatically removed when creating a set.
Use set() to create an empty set, because {} creates an empty dictionary.
Summary
Sets store unique items without order.
Create sets using curly braces or the set() function.
Empty sets must be created with set(), not {}.