Assignment 3 - Solutions

📦 Lists & Dictionaries

Complete solutions with detailed explanations

📋 Questions & Solutions

1 Create a list with numbers 1 to 10 and sort it in ascending and descending order.
# Create list
numbers = [5, 2, 8, 1, 9, 3, 7, 4, 6, 10]

# Ascending order
ascending = sorted(numbers)
print("Ascending:", ascending)

# Descending order
descending = sorted(numbers, reverse=True)
print("Descending:", descending)

# In-place sorting
numbers_copy = numbers.copy()
numbers_copy.sort()
print("In-place sorted:", numbers_copy)
Output
Ascending: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Descending: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
In-place sorted: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

🎓 Explanation

sorted() returns a new sorted list. .sort() modifies in-place. reverse=True for descending order.

2 data = [1,2,3,4,6,7,7,8,9,9]. Drop duplicate values from this list and print the remaining numbers.
data = [1, 2, 3, 4, 6, 7, 7, 8, 9, 9]

# Method 1: Using set (doesn't preserve order)
unique_set = list(set(data))
print("Using set:", unique_set)

# Method 2: Using dict.fromkeys() (preserves order)
unique_ordered = list(dict.fromkeys(data))
print("Preserving order:", unique_ordered)

# Method 3: Loop approach
unique_loop = []
for item in data:
    if item not in unique_loop:
        unique_loop.append(item)
print("Loop method:", unique_loop)
Output
Using set: [1, 2, 3, 4, 6, 7, 8, 9]
Preserving order: [1, 2, 3, 4, 6, 7, 8, 9]
Loop method: [1, 2, 3, 4, 6, 7, 8, 9]

🎓 Explanation

Sets automatically remove duplicates. dict.fromkeys() preserves insertion order (Python 3.7+). Loop method works everywhere but is slower.

3 Write a python code to find the second largest number in a list: [21,44,767,98,37,106,345,87]
numbers = [21, 44, 767, 98, 37, 106, 345, 87]

# Method 1: Sort and get second last
sorted_nums = sorted(numbers, reverse=True)
second_largest = sorted_nums[1]
print("Second largest:", second_largest)

# Method 2: Remove max and find new max
nums_copy = numbers.copy()
nums_copy.remove(max(nums_copy))
second = max(nums_copy)
print("Second largest (remove method):", second)

# Method 3: Single pass (efficient)
first = second = float('-inf')
for num in numbers:
    if num > first:
        second = first
        first = num
    elif num > second and num != first:
        second = num
print("Second largest (single pass):", second)
Output
Second largest: 345
Second largest (remove method): 345
Second largest (single pass): 345

🎓 Explanation

Sorted: [767, 345, 106, 98, 87, 44, 37, 21]. Index [1] = 345. The single-pass method is O(n) vs O(n log n) for sorting.

4 Write a Python program to find the maximum and minimum values in a list: list1 = [21,44,767,98,37]
list1 = [21, 44, 767, 98, 37]

# Using built-in functions
maximum = max(list1)
minimum = min(list1)

print(f"Maximum: {maximum}")
print(f"Minimum: {minimum}")

# Manual approach (without built-in)
max_val = list1[0]
min_val = list1[0]
for num in list1:
    if num > max_val:
        max_val = num
    if num < min_val:
        min_val = num
print(f"\nManual - Max: {max_val}, Min: {min_val}")
Output
Maximum: 767
Minimum: 21

Manual - Max: 767, Min: 21

🎓 Explanation

max() and min() are built-in functions that work on any iterable. The manual method initializes with first element and compares each.

5 Create two separate dictionaries and Merge them.
# Create two dictionaries
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'d': 4, 'e': 5, 'f': 6}

# Method 1: Using ** unpacking
merged1 = {**dict1, **dict2}
print("Method 1 (**):", merged1)

# Method 2: Using update()
merged2 = dict1.copy()  # Don't modify original
merged2.update(dict2)
print("Method 2 (update):", merged2)

# Method 3: Using | operator (Python 3.9+)
merged3 = dict1 | dict2
print("Method 3 (|):", merged3)
Output
Method 1 (**): {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
Method 2 (update): {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
Method 3 (|): {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}

🎓 Explanation

** unpacks dict into key-value pairs. update() modifies in-place. | is cleanest (Python 3.9+). If keys overlap, second dict wins.

6 Write a Python program to create a dictionary where keys are integers from 1 to 5 and corresponding values are their squares.
# Method 1: Dictionary comprehension
squares = {i: i**2 for i in range(1, 6)}
print("Squares:", squares)

# Method 2: Loop approach
squares_loop = {}
for i in range(1, 6):
    squares_loop[i] = i ** 2
print("Squares (loop):", squares_loop)

# Verify
for key, value in squares.items():
    print(f"{key}² = {value}")
Output
Squares: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Squares (loop): {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
1² = 1
2² = 4
3² = 9
4² = 16
5² = 25

🎓 Explanation

Dictionary comprehension {key: value for item in iterable} is concise and Pythonic. i**2 calculates the square.

7 Create a Python dictionary with keys as cars and values as their respective prices.
car_models = ["Toyota Camry", "Honda Civic", "Ford Mustang", "Chevrolet Silverado", "Nissan Altima"]
car_prices = [2500000, 2200000, 4000000, 3500000, 2300000]
car_models = ["Toyota Camry", "Honda Civic", "Ford Mustang", 
              "Chevrolet Silverado", "Nissan Altima"]
car_prices = [2500000, 2200000, 4000000, 3500000, 2300000]

# Using zip() to combine lists into dictionary
car_dict = dict(zip(car_models, car_prices))
print("Car Dictionary:")
for car, price in car_dict.items():
    print(f"  {car}: ₹{price:,}")
Output
Car Dictionary:
  Toyota Camry: ₹2,500,000
  Honda Civic: ₹2,200,000
  Ford Mustang: ₹4,000,000
  Chevrolet Silverado: ₹3,500,000
  Nissan Altima: ₹2,300,000

🎓 Explanation

zip() pairs elements from two lists. dict() converts pairs to dictionary. {price:,} formats with thousands separator.

8 Create a dictionary with 5 key pair values. Key would be a grocery item name and value will be its price (any value in the range of 10 to 1000). Write a for loop to iterate over a dictionary and print key-value pairs. While printing if the value is greater Rs. 500 then print a line – "this is a costly item."
# Create grocery dictionary
grocery = {
    "Rice": 850,
    "Milk": 60,
    "Bread": 45,
    "Olive Oil": 750,
    "Cheese": 520
}

# Iterate and check price
print("Grocery List:")
print("-" * 40)
for item, price in grocery.items():
    print(f"{item}: ₹{price}")
    if price > 500:
        print("  ⚠️ This is a costly item!")
print("-" * 40)
Output
Grocery List:
----------------------------------------
Rice: ₹850
  ⚠️ This is a costly item!
Milk: ₹60
Bread: ₹45
Olive Oil: ₹750
  ⚠️ This is a costly item!
Cheese: ₹520
  ⚠️ This is a costly item!
----------------------------------------

🎓 Explanation

.items() returns key-value pairs for iteration. The condition if price > 500 identifies costly items. Rice, Olive Oil, and Cheese exceed ₹500.

9 In the dictionary created in above task, delete the key value pairs where price is less than average price of all the items in the dictionary.
# Original grocery dictionary
grocery = {
    "Rice": 850,
    "Milk": 60,
    "Bread": 45,
    "Olive Oil": 750,
    "Cheese": 520
}

# Calculate average price
avg_price = sum(grocery.values()) / len(grocery)
print(f"Average price: ₹{avg_price:.2f}")

# Method 1: Dictionary comprehension (create new dict)
filtered = {item: price for item, price in grocery.items() 
            if price >= avg_price}

print(f"\nItems above average (₹{avg_price:.2f}):")
for item, price in filtered.items():
    print(f"  {item}: ₹{price}")
Output
Average price: ₹445.00

Items above average (₹445.00):
  Rice: ₹850
  Olive Oil: ₹750
  Cheese: ₹520

🎓 Explanation

Average = (850+60+45+750+520)/5 = 445. Items below 445 (Milk: 60, Bread: 45) are removed. Dict comprehension filters in one line.

10 Write a python code that takes two sets as input and returns a set containing only the common elements.
# Create two sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

# Method 1: Using & operator
common = set1 & set2
print("Common elements (&):", common)

# Method 2: Using intersection()
common2 = set1.intersection(set2)
print("Common elements (method):", common2)

# Function version
def find_common(s1, s2):
    return s1 & s2

result = find_common({10, 20, 30}, {20, 30, 40})
print("Function result:", result)
Output
Common elements (&): {4, 5}
Common elements (method): {4, 5}
Function result: {20, 30}

🎓 Explanation

Set intersection finds elements in BOTH sets. & operator and .intersection() method are equivalent. Sets are unordered, so output order may vary.