Pythonintermediate 9 min
Python's built-in collections: ordered lists, key-value dictionaries and unique sets.
How to use a list, a dictionary and a set, and which one to choose for the job.
Real programs work with groups of things: names, scores, settings. These three collections cover most cases, and choosing the right one makes code simpler and faster.
List: an ordered, changeable sequence in square brackets, indexed from 0.
Dictionary (dict): key-value pairs in curly braces. Look a value up by its key.
Set: an unordered collection of unique values. Great for removing duplicates and checking membership quickly.
A list comprehension builds a new list in one line: [n * 2 for n in nums if n > 1].
max, min and sum / len give 95 60 82.0.sorted(scores) returns a new sorted list: [60, 72, 88, 95, 95]. The original is unchanged.[95, 88, 95].set(scores) removes the duplicate 95, leaving [60, 72, 88, 95] once sorted.Zoya to the dict and loop over .items(), which gives each key and value: Asha 30, Ravi 25, Zoya 28..get("Maya", "unknown") avoids an error for a missing key and prints unknown.Count how many times each word appears in ["a", "b", "a", "c", "a"] using a dictionary.
dict["key"] on a missing key, which raises KeyError. Use .get() when unsure.{} for an empty set. It creates an empty dict. Use set()..get() for safe dict lookups.Next: reading and writing files.
tags = {"python", "code", "python"} # duplicates removed
"code" in tags # Truenums = [3, 1, 2]
nums.append(4) # add to the end
nums.sort() # [1, 2, 3, 4]
nums[0] # 1
len(nums) # 4user = {"name": "Asha", "age": 30}
user["city"] = "Pune"
user.get("phone", "none") # safe lookup with a defaultscores = [72, 95, 88, 95, 60]
print(max(scores), min(scores), sum(scores) / len(scores))
print(sorted(scores))
high = [s for s in scores if s >= 80]
print(high)
unique = set(scores)
print(sorted(unique))
ages = {"Asha": 30, "Ravi": 25}
ages["Zoya"] = 28
for name, age in ages.items():
print(name, age)
print(ages.get("Maya", "unknown"))