Session 5
π― Sets & Dictionaries
Unique collections and key-value pairs
π 10 Topics
β±οΈ 45 min read
π― Essential Level
πΊοΈ What You'll Learn
Creating Sets
Set Operations
Creating Dictionaries
Keys & Values
Dictionary Methods
Nested Dictionaries
π Same topic in the course notebook
Session_5 Data Structures Part II has tuples, sets, dicts, and methodsβsame content. Open the notebook and run along.
Python Data Structures Comparison
| Feature | List [] | Tuple () | Set {} | Dict {:} |
|---|---|---|---|---|
| Ordered | β Yes | β Yes | β No | β Yes* |
| Mutable | β Yes | β No | β Yes | β Yes |
| Duplicates | β Allowed | β Allowed | β No | β Keys |
| Indexed | β Yes | β Yes | β No | π Keys |
* Dictionaries maintain insertion order since Python 3.7
π― Sets
5.1
π² What is a Set?
A set is an unordered collection of unique items. Think of it like a bag of distinct marbles - no two can be the same!
π― Sets - Like a Unique Collection
LIST SET
[π΄, π΅, π΄, π’] β {π΄, π΅, π’}
β’ Duplicates allowed β’ No duplicates
β’ Has order (0, 1, 2, 3) β’ No fixed order
β’ Can access by index β’ Cannot use index
Sets automatically remove duplicates! β¨
Python
From Source
# Creating sets from Session 4/5
# Using curly braces
fruits = {"apple", "banana", "cherry"}
print("Fruits set:", fruits)
# Using set() constructor
numbers = set([1, 2, 3, 4, 5])
print("Numbers set:", numbers)
# Sets remove duplicates automatically!
with_dupes = {1, 2, 2, 3, 3, 3}
print("Duplicates removed:", with_dupes)
# Empty set - must use set(), not {}
empty_set = set() # Correct!
empty_dict = {} # This is a dictionary, not a set!
print("Empty set type:", type(empty_set))
print("Empty braces type:", type(empty_dict))
# Create set from string
letters = set("hello")
print("Unique letters in 'hello':", letters)
Output
Fruits set: {'cherry', 'apple', 'banana'}
Numbers set: {1, 2, 3, 4, 5}
Duplicates removed: {1, 2, 3}
Empty set type: <class 'set'>
Empty braces type: <class 'dict'>
Unique letters in 'hello': {'h', 'e', 'l', 'o'}
Why Use Sets?
Sets are perfect for: removing duplicates, checking membership (very fast!), and mathematical set operations (union, intersection, etc.)
5.2
β Adding & Removing from Sets
Python
From Source
# Set modifications from Session 4/5
colors = {"red", "green", "blue"}
print("Original:", colors)
# add() - Add single item
colors.add("yellow")
print("After add:", colors)
# update() - Add multiple items
colors.update(["purple", "orange"])
print("After update:", colors)
# remove() - Remove item (error if not found)
colors.remove("yellow")
print("After remove:", colors)
# discard() - Remove item (no error if not found)
colors.discard("pink") # No error even though "pink" doesn't exist
print("After discard:", colors)
# pop() - Remove and return arbitrary item
removed = colors.pop()
print("Popped:", removed)
print("After pop:", colors)
# clear() - Remove all items
colors.clear()
print("After clear:", colors)
Output
Original: {'red', 'green', 'blue'}
After add: {'red', 'green', 'blue', 'yellow'}
After update: {'red', 'green', 'blue', 'yellow', 'purple', 'orange'}
After remove: {'red', 'green', 'blue', 'purple', 'orange'}
After discard: {'red', 'green', 'blue', 'purple', 'orange'}
Popped: red
After pop: {'green', 'blue', 'purple', 'orange'}
5.3
βͺ Set Operations (Math!)
π΅ Venn Diagram of Set Operations
A = {1, 2, 3, 4} B = {3, 4, 5, 6}
βββββββββββββββββββββββββββββββββββ
β A β B β
β βββββββ¬ββββ΄ββββ¬ββββββ β
β β 1,2 β 3,4 β 5,6 β β
β βββββββ΄ββββββββ΄ββββββ β
βββββββββββββββββββββββββββββββββββ
UNION (A | B) = {1, 2, 3, 4, 5, 6} All items
INTERSECTION (A & B) = {3, 4} Common items
DIFFERENCE (A - B) = {1, 2} In A, not in B
SYMMETRIC (A ^ B) = {1, 2, 5, 6} In one, not both
Python
From Source
# Set operations from Session 4/5
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}
print("Set A:", set_a)
print("Set B:", set_b)
# Union - all elements from both sets
union = set_a | set_b # or set_a.union(set_b)
print("\\nUnion (A | B):", union)
# Intersection - elements in both sets
intersection = set_a & set_b # or set_a.intersection(set_b)
print("Intersection (A & B):", intersection)
# Difference - elements in A but not in B
difference = set_a - set_b # or set_a.difference(set_b)
print("Difference (A - B):", difference)
# Symmetric Difference - elements in either, but not both
sym_diff = set_a ^ set_b # or set_a.symmetric_difference(set_b)
print("Symmetric Difference (A ^ B):", sym_diff)
# Subset and Superset checks
small = {1, 2}
big = {1, 2, 3, 4, 5}
print("\\nIs {1,2} subset of {1,2,3,4,5}?", small.issubset(big))
print("Is {1,2,3,4,5} superset of {1,2}?", big.issuperset(small))
Output
Set A: {1, 2, 3, 4}
Set B: {3, 4, 5, 6}
Union (A | B): {1, 2, 3, 4, 5, 6}
Intersection (A & B): {3, 4}
Difference (A - B): {1, 2}
Symmetric Difference (A ^ B): {1, 2, 5, 6}
Is {1,2} subset of {1,2,3,4,5}? True
Is {1,2,3,4,5} superset of {1,2}? True
5.4
πΌ Practical Set Use Cases
Python
From Source
# Practical set examples from Session 4/5
# 1. Remove duplicates from a list
numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
unique = list(set(numbers))
print("Unique numbers:", unique)
# 2. Check membership (very fast!)
valid_users = {"alice", "bob", "charlie"}
user = "bob"
if user in valid_users:
print(f"{user} is a valid user! β
")
# 3. Find common elements
my_skills = {"python", "sql", "excel"}
job_requirements = {"python", "sql", "javascript"}
matching = my_skills & job_requirements
print("Matching skills:", matching)
print("Skills to learn:", job_requirements - my_skills)
Output
Unique numbers: [1, 2, 3, 4]
bob is a valid user! β
Matching skills: {'python', 'sql'}
Skills to learn: {'javascript'}
π Dictionaries
5.5
π What is a Dictionary?
A dictionary stores data in key-value pairs. Think of it like a real dictionary where you look up a word (key) to find its definition (value)!
π Dictionary = Real-World Dictionary
π DICTIONARY
ββββββββββββββββββββββββββββββββββββ
β KEY β VALUE β
β βββββββββββββββββββββββββββββββ β
β "name" β "Alice" β
β "age" β 25 β
β "city" β "New York" β
β "is_student" β True β
ββββββββββββββββββββββββββββββββββββ
Look up by KEY, get back the VALUE! π
Python
From Source
# Creating dictionaries from Session 4/5
# Method 1: Using curly braces
person = {
"name": "Alice",
"age": 25,
"city": "New York",
"is_student": True
}
print("Person:", person)
# Method 2: Using dict() constructor
car = dict(brand="Toyota", model="Camry", year=2022)
print("Car:", car)
# Empty dictionary
empty = {}
print("Empty dict:", empty, "Type:", type(empty))
# Dict from list of tuples
pairs = [("a", 1), ("b", 2), ("c", 3)]
from_tuples = dict(pairs)
print("From tuples:", from_tuples)
Output
Person: {'name': 'Alice', 'age': 25, 'city': 'New York', 'is_student': True}
Car: {'brand': 'Toyota', 'model': 'Camry', 'year': 2022}
Empty dict: {} Type: <class 'dict'>
From tuples: {'a': 1, 'b': 2, 'c': 3}
5.6
π Accessing Dictionary Values
Python
From Source
# Accessing dictionary values from Session 4/5
student = {
"name": "Bob",
"grade": "A",
"age": 20,
"courses": ["Math", "Physics"]
}
# Method 1: Square brackets (raises error if key doesn't exist)
print("Name:", student["name"])
print("Grade:", student["grade"])
# Method 2: get() method (returns None if key doesn't exist)
print("Age:", student.get("age"))
print("Email:", student.get("email")) # Returns None
print("Email (default):", student.get("email", "Not provided"))
# Access nested values
print("First course:", student["courses"][0])
# Check if key exists
if "name" in student:
print("Name key exists! β
")
if "email" not in student:
print("Email key doesn't exist β")
Output
Name: Bob Grade: A Age: 20 Email: None Email (default): Not provided First course: Math Name key exists! β Email key doesn't exist β
5.7
βοΈ Modifying Dictionaries
Python
From Source
# Modifying dictionaries from Session 4/5
product = {"name": "Laptop", "price": 999}
print("Original:", product)
# Add new key-value pair
product["brand"] = "Dell"
print("After adding brand:", product)
# Update existing value
product["price"] = 899
print("After price update:", product)
# update() - Add/update multiple items
product.update({"color": "Silver", "stock": 50})
print("After update():", product)
# Remove items
del product["stock"] # Remove by key
print("After del:", product)
removed_price = product.pop("price") # Remove and return value
print("Removed price:", removed_price)
print("After pop:", product)
# popitem() - Remove last inserted item
last_item = product.popitem()
print("Last item removed:", last_item)
# clear() - Remove all items
product.clear()
print("After clear:", product)
Output
Original: {'name': 'Laptop', 'price': 999}
After adding brand: {'name': 'Laptop', 'price': 999, 'brand': 'Dell'}
After price update: {'name': 'Laptop', 'price': 899, 'brand': 'Dell'}
After update(): {'name': 'Laptop', 'price': 899, 'brand': 'Dell', 'color': 'Silver', 'stock': 50}
After del: {'name': 'Laptop', 'price': 899, 'brand': 'Dell', 'color': 'Silver'}
Removed price: 899
After pop: {'name': 'Laptop', 'brand': 'Dell', 'color': 'Silver'}
Last item removed: ('color', 'Silver')
After clear: {}
5.8
π οΈ Dictionary Methods
Python
From Source
# Dictionary methods from Session 4/5
scores = {"Alice": 95, "Bob": 87, "Charlie": 92}
# keys() - Get all keys
print("Keys:", list(scores.keys()))
# values() - Get all values
print("Values:", list(scores.values()))
# items() - Get key-value pairs as tuples
print("Items:", list(scores.items()))
# Loop through dictionary
print("\\nLooping through keys:")
for name in scores:
print(f" {name}: {scores[name]}")
print("\\nLooping through items:")
for name, score in scores.items():
print(f" {name} scored {score}")
# Length of dictionary
print("\\nNumber of students:", len(scores))
Output
Keys: ['Alice', 'Bob', 'Charlie']
Values: [95, 87, 92]
Items: [('Alice', 95), ('Bob', 87), ('Charlie', 92)]
Looping through keys:
Alice: 95
Bob: 87
Charlie: 92
Looping through items:
Alice scored 95
Bob scored 87
Charlie scored 92
Number of students: 3
5.9
π¦ Nested Dictionaries
Python
From Source
# Nested dictionaries from Session 4/5
company = {
"employee1": {
"name": "Alice",
"department": "Engineering",
"salary": 75000
},
"employee2": {
"name": "Bob",
"department": "Marketing",
"salary": 65000
},
"employee3": {
"name": "Charlie",
"department": "Engineering",
"salary": 70000
}
}
# Access nested values
print("Employee 1's name:", company["employee1"]["name"])
print("Employee 2's dept:", company["employee2"]["department"])
# Loop through nested dictionary
print("\\nAll employees:")
for emp_id, emp_info in company.items():
print(f" {emp_info['name']} - {emp_info['department']} (${emp_info['salary']:,})")
# Modify nested value
company["employee1"]["salary"] = 80000
print("\\nAlice's new salary:", company["employee1"]["salary"])
Output
Employee 1's name: Alice Employee 2's dept: Marketing All employees: Alice - Engineering ($75,000) Bob - Marketing ($65,000) Charlie - Engineering ($70,000) Alice's new salary: 80000
5.10
β‘ Dictionary Comprehension
Python
From Source
# Dictionary comprehension from Session 4/5
# Create dict of squares
squares = {x: x**2 for x in range(1, 6)}
print("Squares:", squares)
# Filter with condition
even_squares = {x: x**2 for x in range(1, 11) if x % 2 == 0}
print("Even squares:", even_squares)
# Transform values
prices = {"apple": 1.00, "banana": 0.50, "cherry": 2.00}
discounted = {item: price * 0.9 for item, price in prices.items()}
print("10% discount:", discounted)
# Create from two lists
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
combined = {name: age for name, age in zip(names, ages)}
print("Combined:", combined)
Output
Squares: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Even squares: {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
10% discount: {'apple': 0.9, 'banana': 0.45, 'cherry': 1.8}
Combined: {'Alice': 25, 'Bob': 30, 'Charlie': 35}
π Quick Reference
π― Set Methods
| Method | Description |
|---|---|
add(x) | Add element |
remove(x) | Remove (error if not found) |
discard(x) | Remove (no error) |
union() or | | All elements from both |
intersection() or & | Common elements |
difference() or - | In first, not second |
π Dictionary Methods
| Method | Description |
|---|---|
get(key) | Get value (None if not found) |
keys() | Get all keys |
values() | Get all values |
items() | Get key-value pairs |
update() | Update with another dict |
pop(key) | Remove and return value |
π« Common Mistakes (Data Structures)
- Using a list as a dict key β Keys must be immutable; use a tuple or string, not a list.
- Expecting set/dict order in old Python β In Python 3.7+ dicts keep insertion order; sets are still unordered.
- mutable default argument β Don't use
def f(x=[]); usedef f(x=None): x = x or []to avoid sharing one list across calls.
π Short reflection
In one sentence: when would you choose a set over a list, and why?
β CORE (Must know)
- Tuple: immutable,
(); use for fixed data. - Set: unordered, unique,
{}; add, remove,in; no duplicates. - Dict: key-value; keys unique; get, keys(), values(), items(), update(), pop().
π NON-CORE (Good to know)
- Defaultdict, Counter; frozenset; dict comprehensions.
Complete code from course notebook: 4_Python_Data_Structures_(1)_(1) (3).ipynb
Every line of code from the course notebook (verbatim).
# --- Code cell 1 ---
# recap---list
# list methods---add/modify,remove,sort,index and count
# --- Code cell 2 ---
# Tuple--methods
# set
# dict
# --- Code cell 4 ---
# seq--string,list and tuple
Exploratory Data Analysis--pandas and matplotlib and seaborn
# --- Code cell 6 ---
list1=[]
type(list1)
# --- Code cell 7 ---
king=[123,"gold",7+7j,456.677,"silver",2345,9765.99,123]
# --- Code cell 8 ---
king[4]
# --- Code cell 9 ---
king[4]="platinum"
# --- Code cell 10 ---
king
# --- Code cell 11 ---
len(king)
print(type(king))
# --- Code cell 12 ---
# list can store data of various types
data = ["rahul",256+6j,47.667,5456,1.0, 2.8,"name",256+6j]
print(data)
print(type(data))
# --- Code cell 14 ---
data = ["rahul",256+6j,47.667,5456,1.0, 2.8,"name",256+6j]
#+ve index-- 0 1 2 3.........
#-ve index .... -3 -2 -1
# --- Code cell 15 ---
data[-5]
# --- Code cell 16 ---
data[1]
# --- Code cell 17 ---
data
# --- Code cell 19 ---
data[1:4]
# --- Code cell 20 ---
data[3:6:1]
# --- Code cell 21 ---
data
# --- Code cell 22 ---
data[-2:-5:1]
# --- Code cell 23 ---
data[-2:-5:-1]
#data[-2:-5:1]
#data[-2:-5:]
# --- Code cell 24 ---
data
# --- Code cell 25 ---
data[1::2]
# --- Code cell 26 ---
start=start======-2
step1=start+step==-2+(-1)=-3
step2=step1+step=-3+(-1)=-4
step3=step2+step=-4+(-1)=-5
step4=step3+step=1+(1)=2
# --- Code cell 27 ---
data[4:7]
# --- Code cell 28 ---
data[1:4:1]
# --- Code cell 29 ---
data[:5]
# --- Code cell 30 ---
king
# --- Code cell 31 ---
king[2]
# --- Code cell 32 ---
king[4]
# --- Code cell 33 ---
king[-4]
# --- Code cell 34 ---
king[-6]
# --- Code cell 35 ---
king2d = [
[123, "gold", 7+7j],
[456.677, "silver", 2345],
[9765.99, 123]
]
# --- Code cell 36 ---
king2d[1][1]
# --- Code cell 37 ---
data
# --- Code cell 38 ---
data[-6:-9:-1]
# --- Code cell 39 ---
data[::2]
# --- Code cell 40 ---
data[0:3:1]
# --- Code cell 41 ---
data[:3:]
# --- Code cell 42 ---
data[2:6:1]
# --- Code cell 43 ---
data[-2,-3]
# --- Code cell 44 ---
data[0:len(data):2]
# --- Code cell 45 ---
data[0:8:2]
# --- Code cell 46 ---
data
# --- Code cell 47 ---
data[-5:-9:-1]
# --- Code cell 48 ---
data[-2:-5:-1]
# --- Code cell 49 ---
start=start:-5
step1=start+step=-5+(-1)=-6
step2=step1+step=-6+(-1)=-7
step3=step2+step=-7+(-1)=-8
step4=step3+step=-8+(-1)=-9
# --- Code cell 50 ---
a = [1,2,3]
# --- Code cell 51 ---
b = a
# --- Code cell 52 ---
c = a[:]
# --- Code cell 53 ---
id(c)
# --- Code cell 54 ---
id(b)
# --- Code cell 55 ---
id(a)
# --- Code cell 56 ---
data[-5]
# --- Code cell 57 ---
data.index(5480)
# --- Code cell 58 ---
len(data)
# --- Code cell 59 ---
data[:2:1]
# --- Code cell 60 ---
data[2:5:1]
# --- Code cell 61 ---
data_list = ["data", "science", "machine", "learning"]
for j in data_list:
print(j)
# --- Code cell 62 ---
data_list = ["data", "science", "machine", "learning"]
if "science1" in data_list:
print("Found, 'science' in the data list")
else:
print("not availavle")
# --- Code cell 65 ---
data_list = ["data", "science", "machine", "learning"]
data_list.insert(2, "maths")
print(data_list)
# --- Code cell 66 ---
data_list[2]="social" # substuting/changing
# --- Code cell 67 ---
data_list
# --- Code cell 68 ---
data_list = ["data", "science", "machine", "learning"]
data_list.insert(2, "maths")
# --- Code cell 69 ---
list_var = [1,2,3, "some data"]
list_var.insert(5,"one more")
print(list_var)
# --- Code cell 73 ---
lst = [1,2,3]
lst.insert(2, 99)
lst
# --- Code cell 75 ---
data_list = ["data", "science", "machine", "learning"]
data_list.append("maths")
print(data_list)
# --- Code cell 76 ---
# adding multiple elements using extend
nums = [1, 2]
nums.extend([3, 4,"new"])
print(nums)
# --- Code cell 77 ---
#adding two lists using +--concadination
data_list = ["data", "science", "machine", "learning","great",455]
science = ['lr',"hello"]
data_list1 = data_list + science
print(data_list1)
# --- Code cell 79 ---
data_list = ["data", "science", "machine", "learning","machine"]
data_list.remove("machine")
print(data_list)
# --- Code cell 81 ---
fruits=["apple","banana","grapes"]
fruits.index("banana")
# --- Code cell 82 ---
data_list = ["data", "science", "machine", "learning"]
data_list.index("machine")
# --- Code cell 84 ---
data_list = ["data", "science", "machine", "learning"]
data_list.pop(1)
data_list
# --- Code cell 85 ---
# removing multiple elements
letters = ['a', 'b', 'c', 'd', 'e']
for item in ["b","d"]:
letters.remove(item)
print(letters)
# --- Code cell 86 ---
list1=[5,1,4,2]
sorted(list1)
list1
# --- Code cell 87 ---
#removing multiple elements using indexing
letters = ['a', 'b', 'c', 'd', 'b']
indexes_to_remove = [4,3,2,1]
for i in sorted(indexes_to_remove, reverse=True):
letters.pop(i)
print(letters)
# --- Code cell 88 ---
#removing multiple elements using indexing without sorted
a= ['a', 'b', 'c', 'd', 'b']
for i in a[:]:
if i == 'b' :
a.remove(i)
print(a)
# --- Code cell 89 ---
data_list = ["data", "science", "machine", "learning"]
data_list.pop(2)
data_list
# --- Code cell 90 ---
list2=[]
list2.pop()
# --- Code cell 91 ---
data_list = ["data", "science", "machine", "learning"]
data_list.pop(2)
print(data_list)
data_list.pop()
print(data_list)
# --- Code cell 92 ---
data_list = ["data", "science", "machine", "learning"]
data_list.append("maths")
data_list.pop(2)
print(data_list)
# --- Code cell 93 ---
fruits = ["apple", "banana", "cherry", "grape"]
fruits.pop(3)
# --- Code cell 94 ---
fruits = ["apple", "banana", "cherry"]
del fruits # Deletes the entire list
# print(fruits) # β This will cause an error (list no longer exists)
fruits
# --- Code cell 95 ---
fruits = ["apple", "banana", "cherry", "grape"]
del fruits
print(fruits)
# --- Code cell 97 ---
data_list = ["data", "science", "machine", "learning"]
del(data_list[0])
print(data_list)
# --- Code cell 98 ---
data_list = ["data", "science", "machine", "learning"]
data_list[0] = "learning"
data_list[3] = "data"
print(data_list)
# --- Code cell 99 ---
del (data_list) # Delete complete list
#print(data_list)
# --- Code cell 101 ---
data_list = ["data", "science", "machine", "learning"]
data_list.clear() # clear the elements from list
print(data_list)
# --- Code cell 103 ---
#sort list
data = [100, 62, 84, 75, 105.0, 72.8]
data.sort() # by defult its ascending order
print(data)
# --- Code cell 104 ---
data.sort(reverse = True) # to get descending order
print(data)
# --- Code cell 106 ---
nums=[2,5,7,1]
nums.sort()
nums
# --- Code cell 107 ---
nums=[2,5,7,1]
sorted(nums)
# --- Code cell 109 ---
#### #copies content from one list to another
import copy
data_list = ["data", "science", "machine", "learning"]
science_list = copy.deepcopy(data_list )
#print(science_list)
data_list.pop()
print(science_list)
print(data_list)
print(id(data_list))
print(id(science_list))
# --- Code cell 111 ---
import copy
# Original nested list
flights = [["AI102", "EK505"], ["QR720", "SQ321"]]
# Shallow copy
shallow_copy = copy.copy(flights)
# Modify inner list
shallow_copy[0][1] = "LH760"
print("Original:", flights)
print("Shallow Copy:", shallow_copy)
print(id(flights[0][1]))
print(id(shallow_copy[0][1]))
# --- Code cell 112 ---
#count and index methods on list
data_list = ["science","data", "science", "machine", "learning","science"]
print("count of word: ", data_list.count("science"))
# --- Code cell 113 ---
print("word found at index: ", data_list.index("science"))
# --- Code cell 115 ---
# -----------------------------------
# Step 1: Start of shift β no flights in queue
# -----------------------------------
landing_queue = [] # list creation
# --- Code cell 116 ---
# -----------------------------------
# Step 2: Flights enter the landing queue
# -----------------------------------
landing_queue.append("AI202") # append
landing_queue.append("BA450")
landing_queue.append("EK713")
# --- Code cell 117 ---
print("Initial Queue:", landing_queue)
# --- Code cell 118 ---
# -----------------------------------
# Step 3: Emergency flight enters (highest priority)
# -----------------------------------
landing_queue.insert(0, "EM999") # insert at beginning
print("After Emergency Flight:", landing_queue)
# --- Code cell 119 ---
# -----------------------------------
# Step 4: Flight information update
# Example: BA450 becomes BA450D (diverted routing)
# -----------------------------------
index = landing_queue.index("BA450") # search
landing_queue[index] = "BA450D" # modify
print("After Update:", landing_queue)
# --- Code cell 120 ---
# -----------------------------------
# Step 5: Flight decides to divert to another airport
# -----------------------------------
landing_queue.remove("EK713") # remove
print("After Diversion:", landing_queue)
# --- Code cell 121 ---
nested = [[1, 2], [1, 2], [3, 4]]
nested.count([1, 2])
# --- Code cell 122 ---
nested.count(1)
# --- Code cell 123 ---
# -----------------------------------
# Step 6: ATC clears the next flight to land
# -----------------------------------
next_landing = landing_queue.pop(0) # pop (first item)
print("Cleared to Land:", next_landing)
print("Remaining Queue:", landing_queue)
# --- Code cell 124 ---
#VIP aircraft from government arrives and must take off first
landing_queue.insert(0, "VIP001")
# --- Code cell 125 ---
# -----------------------------------
# Step 5: Flight decides to divert to another airport
# -----------------------------------
landing_queue.remove("VIP001") # remove
print("After Diversion:", landing_queue)
# --- Code cell 126 ---
# -----------------------------------
# Step 7: Multiple new inbound flights detected
# -----------------------------------
landing_queue.extend(["QR550", "LH330"]) # extend
print("After New Flights:", landing_queue)
# --- Code cell 127 ---
# -----------------------------------
# Step 8: View last flight in queue
# -----------------------------------
print("Last in Queue:", landing_queue[-1])
# --- Code cell 128 ---
# -----------------------------------
# Step 9: Sort by flight number for administrative review
# -----------------------------------
landing_queue.sort()
print("Sorted Queue:", landing_queue)
# --- Code cell 129 ---
# -----------------------------------
# Step 10: Reverse list for runway reallocation plan
# -----------------------------------
landing_queue.reverse()
print("Reversed Queue:", landing_queue)
# --- Code cell 130 ---
# -----------------------------------
# Step 11: Count duplicate flights (rare but possible)
# -----------------------------------
landing_queue.append("QR550") # cargo entry
print("QR550 Count:", landing_queue.count("QR550"))
# --- Code cell 131 ---
# -----------------------------------
# Step 12: Make a copy before resetting the system
# -----------------------------------
backup_queue = landing_queue.copy()
print("Backup Queue:", backup_queue)
# --- Code cell 132 ---
# -----------------------------------
# Step 13: Clear queue at the end of shift
# -----------------------------------
landing_queue.clear()
print("End of Shift Queue:", landing_queue)
# --- Code cell 133 ---
help(list)
# --- Code cell 135 ---
ren=()
type(ren)
# --- Code cell 136 ---
data_tuple = ("data",222,333.44, "machine", "learning")
print(data_tuple)
print(type(data_tuple))
# --- Code cell 137 ---
data_tuple[::-1]
# --- Code cell 138 ---
data_tuple[0]
# --- Code cell 140 ---
data_tuple[0] = 'engineer' # this wont work
# --- Code cell 141 ---
data_tuple = list(data_tuple)
# --- Code cell 142 ---
data_tuple
# --- Code cell 143 ---
# workaround to update tuple
data_tuple[0] = 'engineer'
data_tuple
# --- Code cell 144 ---
data_tuple = tuple(data_tuple)
print(data_tuple)
print(type(data_tuple))
# --- Code cell 145 ---
data_tuple.remove("learning")
# --- Code cell 146 ---
location=(latitudes,longitudes)
location=(23.555,77.9889) # fixed values so that is the reason we will be tuple
# --- Code cell 147 ---
t=(1,[2,3])
t[1].append(4)
# --- Code cell 148 ---
t
# --- Code cell 149 ---
#adding item to tuple
data_tuple = ("data", "science", "machine", "learning")
addition = ("maths",)
data_tuple += addition # data_tuple = data_tuple + addition
type(addition)
# if single is given it takes as a str
# --- Code cell 150 ---
a=1,2,3 # a=(1,2,3)
# --- Code cell 151 ---
type(a)
# --- Code cell 152 ---
nested_tuple=(1,2,(3,4,(5,6)))
nested_tuple
# --- Code cell 153 ---
#adding item to tuple
data_tuple = ("data", "science", "machine", "learning",[77,788])
addition = ("maths",)
data_tuple1 = data_tuple + addition
data_tuple1
# --- Code cell 154 ---
#adding item to tuple
data_tuple = ("data", "science", "machine", "learning")
addition = ["maths",]
data_tuple1 = data_tuple + addition
# --- Code cell 155 ---
#adding item to tuple
data_tuple = ("data", "science", "machine", "learning")
addition = ("maths",)
data_tuple += addition # data_tuple = data_tuple + addition
data_tuple
# --- Code cell 156 ---
#items cannot be removed from tuple
#conversion to list is workaround
data_tuple = ("data", "science", "machine", "learning")
data_tuple = list(data_tuple)
data_tuple.remove("science")
data_tuple = tuple(data_tuple)
data_tuple
# --- Code cell 157 ---
data_tuple
# --- Code cell 158 ---
#for loop on tuple
for x in data_tuple:
print(x)
# --- Code cell 159 ---
days_of_week = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
print(days_of_week[0]) # Output: Monday
# --- Code cell 161 ---
glass={}
type(glass)
# --- Code cell 162 ---
follow={2} # an empty curly braces called dict,if a valued filled then called as set.
type(follow)
# --- Code cell 163 ---
list11=[3,5,3,7,8,2,9,2,88,11,11]
# --- Code cell 164 ---
set(list11)
# --- Code cell 165 ---
list(set(list11))
# --- Code cell 166 ---
data_set = {"data", "science", "machine", "learning","data"}
print(data_set)
print(type(data_set))
# --- Code cell 167 ---
a = {"data", "science", "machine", "learning","science"}
# --- Code cell 168 ---
a
# --- Code cell 169 ---
a[0:3]
# --- Code cell 170 ---
#sets do not hold duplicate values
data_set = {"data", "science", "machine", "learning", "science"}
print(data_set)
# --- Code cell 171 ---
print(data_set[1]) # sets are unordered, cannot be accessed by index
# --- Code cell 172 ---
data_set = {"data", "science", "machine", "learning","data"}
data_set
# --- Code cell 173 ---
#iterating over set
data_set = {"data", "science", "machine", "learning","data"}
for value in data_set:
print(value)
# --- Code cell 174 ---
data_set = {"data", "science", "machine", "learning"}
if "science1" in data_set:
print("yes")
else:
print("no")
# --- Code cell 176 ---
data_set = {"data", "science", "machine", "learning"}
data_set.add("maths")
data_set
# --- Code cell 177 ---
evens = set(range(0, 21, 2))
print(evens)
# --- Code cell 178 ---
data_set = {"data", "science","learning",True,None,"machine"}
data_set.pop()
data_set
# --- Code cell 180 ---
# Add two sets
data_set = {"data", "science", "machine", "learning"}
machine_set = {"lr", "svm", "kmeans"}
data_set.update(machine_set)
data_set
# --- Code cell 182 ---
data_set = {"data", "science", "machine", "learning"}
data_set.remove("machine12")
print(data_set)
# --- Code cell 183 ---
data_set = {"data", "science", "machine", "learning"}
data_set.discard("machine1")
print(data_set)
# --- Code cell 185 ---
# union()
# Combine elements from sets (no duplicates).
a = {1, 2}
b = {2, 3}
print(a.union(b))
# --- Code cell 186 ---
# intersection()
# Common elements.
a = {1, 2, 3}
b = {2, 3, 4}
print(a.intersection(b))
# --- Code cell 187 ---
# difference()
# Elements in set A but not in B.
a = {1, 2, 3}
b = {2, 4}
print(a.difference(b))
# --- Code cell 188 ---
emails=["a@gmail.com","b@gmail.com","c@gmail.com","a@gmail.com"]
unique_emails=set(emails)
unique_emails
# --- Code cell 190 ---
dictionary = {
"company": "Inttrvu",
"website": "Inttrvu.ai",
"year": 2023,
"type": "Edtech",
"city": "Pune"
}
print(dictionary)
# --- Code cell 191 ---
dictionary[0]
# --- Code cell 192 ---
print(list(dictionary)[2])
# --- Code cell 193 ---
dictionary["company"]
# --- Code cell 194 ---
list(dictionary)
# --- Code cell 195 ---
dictionary.keys() #get all keys
# --- Code cell 196 ---
dictionary.values() #get all values
# --- Code cell 197 ---
dictionary.items() # to get all the comb
# --- Code cell 198 ---
print(dictionary.get("company")) # get value of specific key
# --- Code cell 199 ---
dictionary
# --- Code cell 200 ---
dictionary["city"]= "bangalore" # change value of dictionary key
dictionary
# --- Code cell 201 ---
#Add new item to dictionary
dictionary["course"]= "data_science"
dictionary
# --- Code cell 202 ---
dictionary.update({"city": "Pune","location":"green field"}) # change value of dictionary key
dictionary
# --- Code cell 203 ---
dictionary.update({"location": "Mumbai"}) # if this key is not present then it would be added , if found value if overwritten
dictionary
# --- Code cell 204 ---
dictionary.update({"country": "India"}) # if this key is not present then it would be added , if found value if overwritten
dictionary
# --- Code cell 205 ---
# Duplicate keys are not allowed
dictionary = {
"company": "Inttrvu",
"website": "Inttrvu.ai",
"year": 2023,
"type": "Edtech",
"city": "Pune",
"city": "Mumbai"
}
print(dictionary)
# --- Code cell 206 ---
# Delete specific key value pair
dictionary.pop("city")
print(dictionary)
# --- Code cell 207 ---
dictionary.values()
# --- Code cell 209 ---
# Looping through keys and values of dictionary
for v in dictionary.values():
print(v)
# --- Code cell 210 ---
for k in dictionary.keys(): # Looping through only keys
print(k)
# --- Code cell 211 ---
for v in dictionary.values(): # Looping through only values
print(v)
# --- Code cell 213 ---
# -------------------------------------------------------
# Restaurant table availability (SET)
# -------------------------------------------------------
available_tables = {1, 2, 3, 4, 5} # Table numbers
# --- Code cell 214 ---
# -------------------------------------------------------
# Booked table details (DICTIONARY)
# table_number : customer_name
# -------------------------------------------------------
bookings = {}
print("Initial Available Tables:", available_tables)
# --- Code cell 215 ---
# -------------------------------------------------------
# 1. Customer books a table
# -------------------------------------------------------
customer = "Arjun"
book_table = 3
if book_table in available_tables:
bookings[book_table] = customer # add to dictionary
available_tables.discard(book_table) # remove from available
print(f"\nTable {book_table} booked for {customer}")
else:
print(f"\nTable {book_table} is not available.")
# --- Code cell 216 ---
# -------------------------------------------------------
# 2. Another customer books a table
# -------------------------------------------------------
customer2 = "Priya"
book_table2 = 1
if book_table2 in available_tables:
bookings[book_table2] = customer2
available_tables.discard(book_table2)
print(f"Table {book_table2} booked for {customer2}")
else:
print(f"Table {book_table2} is not available.")
print("\nAvailable Tables:", available_tables)
print("Current Bookings:", bookings)
# --- Code cell 217 ---
# -------------------------------------------------------
# 3. Customer cancels a booking
# -------------------------------------------------------
cancel_table = 3
if cancel_table in bookings:
cancelled_customer = bookings[cancel_table]
del bookings[cancel_table] # remove customer from dictionary
available_tables.add(cancel_table) # add table back to availability
print(f"\nBooking cancelled for {cancelled_customer} at table {cancel_table}")
else:
print("\nNo booking found at that table.")
print("\nAvailable Tables after cancellation:", available_tables)
print("Bookings after cancellation:", bookings)
# --- Code cell 218 ---
# -------------------------------------------------------
# 4. Checking fully booked or not
# -------------------------------------------------------
if len(available_tables) == 0:
print("\nRestaurant is fully booked.")
else:
print("\nTables still available:", available_tables)
# --- Code cell 219 ---
# -------------------------------------------------------
# 5. Print all customers seated
# -------------------------------------------------------
print("\n customers currently seated:")
for table, customer in bookings.items():
print(f"Table {table}: {customer}")