![]() |
| Python tutorial explaining range function and dictionary operations including update, pop, clear, and key value pairs with examples. |
🔢 Python Range
range() is used to generate a sequence of numbers. It is useful to create number series like:
1 2 3 4 5 6
1 3 5 7 9 11
Syntax:
range(start, end, step)
start → Starting number end → Ending number (not included) step → Gap between numbers
Example 1
range_2 = range(5, 12) print(range_2)
Output:
range(5, 12)
This generates numbers from 5 to 11.
Example 2
range_3 = range(7) print(range_3)
Output:
range(0, 7)
If only one value is given, it starts from 0.
Example with Step
print(list(range(1, 12, 2)))
Output:
[1, 3, 5, 7, 9, 11]
Step value creates a gap between numbers.
📘 Python Dictionaries
A Dictionary stores data in key : value pairs. It is ordered, changeable, and does not allow duplicate keys.
📌 Creating a Dictionary
this_dict = {
"name": "sherul",
"weight": "1kg",
"price": 130.35
}
print(this_dict)
print(type(this_dict))
Output type:
🚫 No Duplicate Keys
If you add duplicate key, it will override the previous value.
this_dict = {
"name": "sherul",
"weight": "1kg",
"price": 130.35,
"price": 150
}
print(this_dict)
Output:
{'name': 'sherul', 'weight': '1kg', 'price': 150}
🔍 Access Values
print(this_dict["name"])
print(this_dict.get("weight"))
✏ Update Value
this_dict["weight"] = 150
print(this_dict.get("weight"))
📏 Length of Dictionary
print(len(this_dict))
Returns total number of items.
➕ Add New Item
this_dict["color"] = "white" print(this_dict)
🔄 Update Multiple Items
this_dict.update({"expire_date": "2025", "weight": 120})
print(this_dict)
🗑 Remove Items
pop() removes specific key:
this_dict.pop("weight")
print(this_dict)
popitem() removes last inserted item:
this_dict.popitem() print(this_dict)
del removes specific key:
del this_dict["name"] print(this_dict)
clear() makes dictionary empty:
this_dict.clear() print(this_dict)
📦 Dictionary Values Can Be Any Type
my_dict = {
"name": "Alice",
"age": 25,
"hobbies": ["reading", "cycling"],
"skills": {"Python", "SQL"},
"address": {
"city": "Colombo",
"zip": "10100"
},
"marks": (85, 90, 78),
"is_active": True
}
Dictionary values can be list, set, tuple, or even another dictionary.
🔐 Rules for Dictionary Keys
Keys must be immutable.
- ✔ String
- ✔ Integer
- ✔ Tuple
- ❌ List
- ❌ Dictionary
- ❌ Set
🎯 Dictionaries are powerful for storing structured data. They are widely used in APIs, JSON data, and Data Science 🚀.
