ASSIGNMENT
Submitted to : Ms. Anza Jabbar
Submitted by : Syeda Rutab Aziz
Registration no : COSC232101044
Class : BSCS 4A
Course : AI LAB
Topic : Sets and Tuples
Date Submitted : 25 - 11 - 2024
Sets
Definition
Sets are unordered collections of unique items. They are mutable but do not allow
duplicate elements.
Characteristics
Unordered: Items do not have a defined order.
Unique: No duplicate elements are allowed.
Syntax
# Creating a set
my_set = {1, 2, 3, 'apple'}
Common Operations
Adding Elements: Use add() to add a single item.
my_set.add('banana')
print(my_set) # Output: {1, 2, 3, 'apple', 'banana'}
Removing Elements: Use remove() to remove a specific item.
my_set.remove('apple')
print(my_set) # Output: {1, 2, 3, 'banana'}
Membership: Check if an item exists using the in keyword.
if 'banana' in my_set:
print('Banana is in the set') # Output: Banana is in the set
Union: Combine two sets using the | operator.
another_set = {4, 5}
combined_set = my_set | another_set
print(combined_set) # Output: {1, 2, 3, 4, 5, 'banana'}
Intersection: Find common elements using the & operator.
common_set = my_set & another_set
print(common_set) # Output: set()
Dictionaries
Definition
Dictionaries are mutable collections of key-value pairs. Each key must be unique.
Characteristics
Key-Value Pairs: Each element is a pair consisting of a key and a value.
Mutable: You can change, add, or remove items.
Syntax
# Creating a dictionary
my_dict = {'name': 'Alice', 'age': 25}
Common Operations
Accessing Values: Use the key to access the value.
print(my_dict['name']) # Output: Alice
Modifying Values: Assign a new value to a specific key.
my_dict['age'] = 26
print(my_dict) # Output: {'name': 'Alice', 'age': 26}
Adding Key-Value Pairs: Assign a value to a new key.
my_dict['city'] = 'New York'
print(my_dict) # Output: {'name': 'Alice', 'age': 26, 'city': 'New York'}
Removing Key-Value Pairs: Use del to remove a specific key.
del my_dict['age']
print(my_dict) # Output: {'name': 'Alice', 'city': 'New York'}
Membership: Check if a key exists using the in keyword.
if 'name' in my_dict:
print('Name is a key in the dictionary') # Output: Name is a key in the dictionary
Key Differences
Feature Set Dictionary
Mutability Mutable (changeable) Mutable (changeable)
Syntax Curly brackets {} Curly brackets {}
Performance Faster due to uniqueness Faster due to key-value
pairs
Use Cases Unique collections Key-value pair collections
Conclusion
Lists, tuples, sets, and dictionaries are fundamental data structures in Python. Choose lists when you need
a mutable collection of items, tuples when you need an immutable collection, sets when you need a unique
collection, and dictionaries when you need a key-value pair collection. Understanding these differences
will help you make efficient decisions in your Python programming.