Module 1 Python
Module 1 Python
1.
Dictionaries
Syntax:
A dictionary is created using curly braces {} with key-value pairs.
my_dict = {"name": "Bob", "age": 30}
Characteristics:
Unordered before Python 3.7; now maintains insertion order.
Mutable: Values can be added, updated, or removed.
Keys are unique and must be immutable (e.g., strings, numbers).
Useful for fast lookups using keys.
Example:
student = {"name": "John", "grade": "A"}
print(student["grade"]) # Output: A
student["grade"] = "A+" # Updating value
print(student) # Output: {'name': 'John', 'grade': 'A+'}
Comparison Table
Feature Tuple Dictionary
Syntax () {}
Sample Output:
Enter numbers separated by commas: 10, 20, 30, 40
Sum: 100
Average: 25.0
3. Explain the following list functions with examples and
explanation:
a) append():
- Adds a single item to the end of the list.
Example:
fruits = ["apple", "banana"]
fruits.append("orange")
print(fruits) # ['apple', 'banana', 'orange']
b) extend():
- Adds multiple elements from another list to the end.
Example:
fruits = ["apple", "banana"]
fruits.extend(["orange", "grape"])
print(fruits) # ['apple', 'banana', 'orange', 'grape']
c) insert():
- Inserts an element at a specific index.
Example:
fruits = ["apple", "banana"]
fruits.insert(1, "orange")
print(fruits) # ['apple', 'orange', 'banana']
d) index():
- Returns the index of the first occurrence of a value.
Example:
fruits = ["apple", "banana", "orange"]
print(fruits.index("orange")) # 2
4. Write a Python program to make a new list that will store squares
of elements from the existing list [10, 8, 6, 4, 2].
Code:
numbers = [10, 8, 6, 4, 2]
squares = [x**2 for x in numbers]
print("Original list:", numbers)
print("Squares list:", squares)
Output:
Original list: [10, 8, 6, 4, 2]
Squares list: [100, 64, 36, 16, 4]