> Everything is an object: a key difference from C++
In Python, values such as integers, strings, lists, and functions are all objects. They have types and methods, which is different from C++ primitive values.
| Function | Purpose |
| --- | --- |
| `type()` | returns the type of an object |
| `dir()` | lists the available attributes and methods |
```python
type(5) type(“hello”)
```python
dir(int)
```
> Methods wrapped in `__...__` are called magic methods. They allow Python to implement operators like `+`, `==`, `[]`, and `len()`.
```python
a = 5
b = 3
print(a + b)
```
---
## Container types
### 1. List
Lists are ordered, mutable sequences.
```python
a = [1, "hi", 3.14]
a.append(5)
print(a)
```
### 2. Tuple
Tuples are ordered, immutable sequences.
```python
b = (5, "Xiao is handsome", True)
print(b)
```
### 3. Dictionary
Dictionaries store key-value pairs.
```python
d = {"apple": 5, "banana": 8}
d["apple"] = 10
print(d)
```
### 4. Set
Sets store unique elements.
```python
s = {1, 2, 3, 3, 1, 4}
s.add(8)
print(s)
```
## Example exercises
### Exercise 1: Count occurrences
```python
labels = ["cat", "dog", "cat", "rabbit", "dog", "cat"]
count = {}
for label in labels:
if label in count:
count[label] += 1
else:
count[label] = 1
print(count)
```
### Exercise 2: Reverse a score dictionary
```python
scores = {'Amy': 85, 'Bob': 90, 'Cathy': 85, 'David': 92}
new = {}
for student in scores.keys():
if scores[student] in new:
new[scores[student]].append(student)
else:
new[scores[student]] = [student]
print(new)
```
## Summary
Python is object-oriented, flexible, and expressive. The correct understanding of objects and container types is fundamental to writing clean Python programs.