Page 447 - ComputerScience_Class_11
P. 447
12.7 SET
A set is a collection of unordered, unique and mutable elements in Python. It allows you to store multiple items,
but does not allow duplicates and the order of elements is not maintained. Sets are unordered, you cannot access
elements using an index, but you can iterate through them using loops.
Program 14: To display the unique numbers stored in a variable.
Program 14.py
File Edit Format Run Options Window Help
# Creating a set of numbers
numbers = {50, 3, 18, 7, 22, 1, 10 }
# Printing the set
print("Set of numbers:",numbers)
Output
Set of numbers: {1, 18, 3, 50, 22, 7, 10}
12.7.1 Characteristics of Set data types in Python
There are some characteristics of Set data types in Python:
• Collection of Distinct Elements: A set automatically removes duplicate values and stores only unique items.
• Unordered Structure: Elements are not stored in a fixed position and the order may change.
• Mutable Data Type: You can add or remove elements using methods like add() and remove().
• No Duplicate Entries: If duplicate values are provided, only one copy is kept in the set.
• Supports Membership Testing: Operators like in and not in can be used to check whether an element exists in
the set.
• Elements Must Be Immutable: Only immutable data types (such as numbers, strings or tuples) can be stored as
elements in a set.
• Efficient for Searching: Sets provide fast lookup and membership testing compared to other collection types.
• Can Perform Mathematical Set Operations: Useful for operations like union, intersection, difference and symmetric
difference.
12.8 MUTABLE AND IMMUTABLE
In Python, every variable is an object with a property called mutability, which shows whether its contents can be
changed. Mutable objects can be modified after creation, while immutable objects cannot. Understanding this helps
write efficient and error-free code.
12.8.1 Mutable Data Types
Mutable data types are types of objects in Python whose values can be changed after they are created. You can
modify, add or remove elements without creating a new object in memory. Mutable objects can be homogeneous,
meaning they can contain elements of the same data type. Examples of mutable data types include sets.
Data Types in Python 445

