A set in Python is a collection used to store unique items, meaning duplicate values are not allowed.
Sets are written using curly braces { } .
Python
numbers = {10, 20, 30, 20} print(numbers) #output {10, 20, 30} Features of Sets :
1. Stores Unique Elements . Duplicates Values are automatically removed.
2. Unordered . They do not follow index positions.
3. Set Elements are Immutable . Only numbers , strings and tuples are allowed.
4. Mutable .
Accessing Set Elements :
Since sets are unordered , they do not support indexing or slicing.
Python
s = {10, 20, 30} print(s[0]) # Not allowed Access using Loop :
Use a simple for loop to access element.
Python
fruits = {"apple", "banana", "mango"} for item in fruits: print(item) #output apple mango banana #The order may Change Convert to List (If indexing is required ) :
Python
s = {"red", "blue", "green"} lst = list(s) print(lst[0])