Which one do I use?
| Type | Looks like | Can change? | Duplicates? | Use it for |
|---|---|---|---|---|
| list | [1, 2, 3] | Yes | Allowed | An ordered collection |
| tuple | (1, 2, 3) | No | Allowed | Fixed data, like a coordinate |
| set | {1, 2, 3} | Yes | Removed | Unique items |
| dict | {"a": 1} | Yes | Keys are unique | Looking up by name |
Tuples
point = (4, 7)
print(point[0])
x, y = point # Unpacking
print(x, y)
try:
point[0] = 9
except TypeError as error:
print("Can't change a tuple:", error)Output
4 4 7 Can't change a tuple: 'tuple' object does not support item assignment
Sets
a = {1, 2, 3, 3, 3}
b = {3, 4}
print(len(a)) # Duplicates are gone
print(sorted(a | b)) # In either
print(sorted(a & b)) # In both
print(sorted(a - b)) # In a, not in bOutput
3 [1, 2, 3, 4] [3] [1, 2]
Dictionaries
student = {"name": "Riya", "age": 14, "marks": [78, 85]}
print(student["name"])
print(student.get("city", "Not given")) # Safe if the key is missing
student["city"] = "Pune" # Add
student["age"] = 15 # Change
del student["marks"] # Remove
for key, value in student.items():
print(key, "->", value)Output
Riya Not given name -> Riya age -> 15 city -> Pune
# A classic: count words with a dictionary
text = "free money free prize free"
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
print(counts)Output
{'free': 3, 'money': 1, 'prize': 1}Code challenge
Make a dictionary of 3 subjects and marks, then print the subject with the highest marks.
max(marks, key=marks.get) gives the key with the largest value.
Finished reading?