Python

> 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.

Related articles

Introduction to Linux

An operating system sits between users and hardware. It manages memory, processes, files, and devices while exposing a graphical or command-line interface. - Linux - iOS - Android - macOS - Windows…

Training

Poetry

This file defines project metadata and dependencies. This file pins the exact dependency versions used in the project for reproducibility. --- --- Poetry is ideal for clean, reproducible Python pro…

Training

Git

Git is a distributed version control system (DVCS) used to: - track changes to files over time - collaborate with multiple people on the same project - manage branches independently - sync code wit…

Training

Advanced Packaging Tool

This document contains frequently used command and the corresponding used cases for package management software Advanced Packaging Tool (APT). For simplification, all the variables are written in p…

Training