XGBoost Python Tutorial (XGBoost 3): Classification, Early Stopping, SHAP, Optuna Tuning and Quantile Regression (2026)

Data Sciences Dec 05, 2026

Watch on YouTube

XGBoost is still the model to beat on tabular data. Whether you are predicting customer churn, fraud, prices or delivery times from a spreadsheet-like table, a well-tuned gradient boosted tree model usually wins against deep learning and is far cheaper to train. The library has also changed a lot since most tutorials online were written: XGBoost 3 removed old APIs, version 3.3 (June 2026) turned on native categorical support by default and deprecated the linear booster, and version 3.4 (August 2026) deprecated the random forest wrappers and moved the default Linux and Windows wheels to CUDA 13. In this XGBoost Python tutorial we build a complete churn model with XGBoost 3.4.1: native categorical features, early stopping, a saved JSON model, feature importance, per-customer SHAP explanations, Optuna hyperparameter tuning, and finally prediction intervals with quantile regression. Every output block below is the real output of the script above it.

What you will build

  • A reproducible customer churn dataset with numeric and categorical columns (generated by code, so everything runs offline).
  • An XGBClassifier that uses pandas category columns directly, with early stopping on a validation set.
  • A saved .json model, global feature importance and SHAP values that explain one customer's prediction.
  • An Optuna study that tunes six hyperparameters, and an honest comparison of tuned versus default settings.
  • An XGBRegressor that predicts the 10th, 50th and 90th percentile of delivery time in a single model.

Setup

uv venv -p 3.14 && source .venv/bin/activate
uv pip install xgboost-cpu scikit-learn pandas optuna
python step1_train.py

Since the 3.4 release the default xgboost wheel on Linux and Windows is built with CUDA 13 and is a large download. If you train on CPU (laptops, CI runners, most Docker images), install xgboost-cpu instead: it is the same Python package, imported as import xgboost, without the GPU libraries. If you have an NVIDIA GPU, install xgboost (or xgboost-cu12 for older CUDA 12 drivers) and pass device="cuda". Note that XGBoost 3.3+ needs Python 3.12 or newer (the 3.4.2 and 3.3.1 patch releases added Python 3.11 wheels back).

Step 1: Train an XGBClassifier with categorical features and early stopping

Our dataset has 6,000 telecom customers with tenure, monthly charges, support calls, data usage, contract type, payment method and region. The churn label is generated from a known formula plus randomness, so we know that contract, tenure, support calls, charges and payment really matter, while data_gb and region are pure noise. That makes it a great playground for checking whether the model and its explanations are telling the truth.

import numpy as np
import pandas as pd
import xgboost as xgb
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, roc_auc_score, confusion_matrix

# 1) A reproducible customer churn dataset (6,000 customers)
rng = np.random.default_rng(7)
n = 6000
df = pd.DataFrame({
    "tenure_months": rng.integers(1, 73, n),
    "monthly_charges": rng.normal(70, 25, n).clip(15, 150).round(2),
    "support_calls": rng.poisson(1.5, n),
    "data_gb": rng.gamma(2.0, 10.0, n).round(1),
    "contract": rng.choice(["month-to-month", "one-year", "two-year"], n, p=[0.55, 0.25, 0.20]),
    "payment": rng.choice(["card", "bank", "e-check"], n, p=[0.4, 0.3, 0.3]),
    "region": rng.choice(["north", "south", "east", "west"], n),
})
logit = (-2.0 - 0.045 * df.tenure_months + 0.022 * df.monthly_charges + 0.45 * df.support_calls
         + df.contract.map({"month-to-month": 1.3, "one-year": -0.2, "two-year": -1.4})
         + df.payment.map({"card": -0.2, "bank": -0.3, "e-check": 0.6}))
df["churn"] = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
for col in ["contract", "payment", "region"]:
    df[col] = df[col].astype("category")          # XGBoost 3.3+ uses category columns natively
df.to_csv("churn.csv", index=False)
print("rows:", len(df), "| churn rate:", f"{df.churn.mean():.1%}")
print(df.dtypes.to_string())

# 2) train / validation / test split
X, y = df.drop(columns="churn"), df["churn"]
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)
X_tr, X_va, y_tr, y_va = train_test_split(X_tr, y_tr, test_size=0.2, stratify=y_tr, random_state=42)
print("train/valid/test:", len(X_tr), len(X_va), len(X_te))

# 3) XGBClassifier with early stopping on the validation set
model = xgb.XGBClassifier(
    n_estimators=2000, learning_rate=0.05, max_depth=4,
    subsample=0.8, colsample_bytree=0.8,
    eval_metric="auc", early_stopping_rounds=50,
    tree_method="hist", random_state=42, n_jobs=4,
)
model.fit(X_tr, y_tr, eval_set=[(X_va, y_va)], verbose=200)
print("best iteration:", model.best_iteration, "| best valid AUC:", round(model.best_score, 4))

# 4) evaluate on the untouched test set
proba = model.predict_proba(X_te)[:, 1]
pred = (proba >= 0.5).astype(int)
print("test accuracy:", round(accuracy_score(y_te, pred), 4))
print("test ROC AUC: ", round(roc_auc_score(y_te, proba), 4))
print("confusion matrix [[TN FP] [FN TP]]:", confusion_matrix(y_te, pred).tolist())

# 5) save the model in the portable JSON format
model.save_model("churn_xgb.json")
print("saved churn_xgb.json")
rows: 6000 | churn rate: 33.7%
tenure_months         int64
monthly_charges     float64
support_calls         int64
data_gb             float64
contract           category
payment            category
region             category
churn                 int64
train/valid/test: 3840 960 1200
[0]	validation_0-auc:0.79489
[150]	validation_0-auc:0.84429
best iteration: 100 | best valid AUC: 0.845
test accuracy: 0.78
test ROC AUC:  0.8325
confusion matrix [[TN FP] [FN TP]]: [[708, 87], [177, 228]]
saved churn_xgb.json

A few things are worth noticing. First, there is no one-hot encoding and no enable_categorical=True: since XGBoost 3.3 the estimator reads pandas category columns natively, finding the best grouping of categories at each split. You still have to convert string columns to the category dtype; plain object or str columns raise an error. If you want a full preprocessing pipeline with scaling, imputing and one-hot encoding for other models, see our scikit-learn Pipeline and ColumnTransformer tutorial.

Second, we asked for 2,000 trees but used early stopping: early_stopping_rounds=50 is now a constructor argument (passing it to fit() was removed in XGBoost 3), and training stopped when the validation AUC had not improved for 50 rounds. The best model was at iteration 100 with a validation AUC of 0.845, and predict and predict_proba automatically use that best iteration. Always keep a separate test set that the model never saw during early stopping or tuning; here the test ROC AUC is 0.8325 and accuracy is 0.78 at a churn rate of 33.7%.

Third, accuracy hides the business problem. The confusion matrix shows 228 churners caught and 177 missed, with 87 false alarms. If missing a churner is expensive, lower the 0.5 threshold on predict_proba or set scale_pos_weight to the ratio of negatives to positives.

Finally, save_model("churn_xgb.json") writes the portable JSON format (or .ubj for compact binary JSON). Do not pickle XGBoost models for long-term storage: JSON models load in any future XGBoost version and in the R, JVM and C APIs, and they keep the category mapping. To version and deploy models across a team, combine this with a registry like the one in our MLflow model registry guide.

Step 2: Load the model, feature importance and SHAP values

A churn model is only useful if you can explain it to the retention team. XGBoost has two levels of explanation built in: global feature importance for the whole model, and SHAP values that explain one prediction. You do not need the separate shap package for tree models; pred_contribs=True computes exact TreeSHAP values inside XGBoost, and the 3.3 release made this faster and more numerically stable.

import numpy as np
import pandas as pd
import xgboost as xgb
from sklearn.model_selection import train_test_split

df = pd.read_csv("churn.csv", dtype={"contract": "category", "payment": "category", "region": "category"})
X, y = df.drop(columns="churn"), df["churn"]
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)

# 1) load the saved model and check it predicts exactly like before
model = xgb.XGBClassifier()
model.load_model("churn_xgb.json")
print("loaded trees:", model.get_booster().num_boosted_rounds(), "| best_iteration:", model.best_iteration)

# 2) global feature importance (average gain per split)
gain = model.get_booster().get_score(importance_type="gain")
total = sum(gain.values())
print("\nfeature importance (gain share):")
for name, g in sorted(gain.items(), key=lambda kv: -kv[1]):
    print(f"  {name:16s} {g / total:6.1%}")

# 3) SHAP values for one customer, built into XGBoost (pred_contribs=True)
customer = X_te.iloc[[0]]
print("\ncustomer:", customer.to_dict("records")[0])
dm = xgb.DMatrix(customer, enable_categorical=True)
booster = model.get_booster()
contribs = booster.predict(dm, pred_contribs=True, iteration_range=(0, model.best_iteration + 1))[0]
names = list(X.columns) + ["bias"]
print("SHAP contributions (log-odds):")
for name, c in sorted(zip(names, contribs), key=lambda kv: -abs(kv[1])):
    print(f"  {name:16s} {c:+.3f}")
margin = contribs.sum()
print(f"sum of contributions = {margin:.3f} -> churn probability {1 / (1 + np.exp(-margin)):.3f}")
print(f"model.predict_proba                  -> churn probability {model.predict_proba(customer)[0, 1]:.3f}")
loaded trees: 151 | best_iteration: 100

feature importance (gain share):
  contract          38.9%
  tenure_months     17.7%
  support_calls     14.0%
  payment           10.1%
  monthly_charges    9.5%
  data_gb            5.2%
  region             4.4%

customer: {'tenure_months': 43, 'monthly_charges': 15.0, 'support_calls': 1, 'data_gb': 13.2, 'contract': 'month-to-month', 'payment': 'card', 'region': 'west'}
SHAP contributions (log-odds):
  monthly_charges  -0.960
  bias             -0.687
  contract         +0.627
  tenure_months    -0.368
  support_calls    -0.211
  payment          -0.198
  data_gb          -0.028
  region           +0.028
sum of contributions = -1.797 -> churn probability 0.142
model.predict_proba                  -> churn probability 0.142

The loaded model contains 151 trees (the best iteration plus the 50 extra rounds early stopping waited for), and it remembers best_iteration, so predictions after loading match the original model. The gain-based importance puts contract first at 38.9%, followed by tenure and support calls, which matches how we generated the data. The two noise columns, data_gb and region, still receive 5.2% and 4.4%: trees always find some small accidental pattern in noise, so never treat a low importance as proof that a feature is useful.

The SHAP output explains a single customer in log-odds. The bias (-0.687) is the average prediction, a very low monthly charge pushes the prediction down (-0.960), and the month-to-month contract pushes it up (+0.627). The contributions add up exactly to the model's raw score, and the sigmoid of that sum gives the same churn probability, 0.142, as predict_proba. Note the iteration_range argument: when you call the low-level Booster.predict you must pass the best iteration yourself, otherwise all 151 trees are used. To plot these numbers as interactive bar charts, see our Plotly Express charts tutorial.

Step 3: Tune XGBoost hyperparameters with Optuna

XGBoost has many knobs, but six matter most: learning_rate, max_depth, min_child_weight, subsample, colsample_bytree and reg_lambda. Grid search over six parameters is far too slow, so we use Optuna (version 5.1.0, released in November 2026) with its TPE sampler, which learns from earlier trials which regions of the search space look promising. Each trial uses early stopping, so we never have to tune n_estimators.

import optuna
import pandas as pd
import xgboost as xgb
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score

df = pd.read_csv("churn.csv", dtype={"contract": "category", "payment": "category", "region": "category"})
X, y = df.drop(columns="churn"), df["churn"]
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)
X_tr, X_va, y_tr, y_va = train_test_split(X_tr, y_tr, test_size=0.2, stratify=y_tr, random_state=42)

def make_model(**params):
    return xgb.XGBClassifier(n_estimators=2000, eval_metric="auc", early_stopping_rounds=50,
                             tree_method="hist", random_state=42, n_jobs=4, **params)

def objective(trial):
    params = {
        "learning_rate": trial.suggest_float("learning_rate", 0.01, 0.3, log=True),
        "max_depth": trial.suggest_int("max_depth", 2, 8),
        "min_child_weight": trial.suggest_float("min_child_weight", 1, 20, log=True),
        "subsample": trial.suggest_float("subsample", 0.5, 1.0),
        "colsample_bytree": trial.suggest_float("colsample_bytree", 0.5, 1.0),
        "reg_lambda": trial.suggest_float("reg_lambda", 0.1, 50, log=True),
    }
    model = make_model(**params).fit(X_tr, y_tr, eval_set=[(X_va, y_va)], verbose=False)
    trial.set_user_attr("trees", model.best_iteration + 1)
    return model.best_score                       # validation AUC at the best iteration

optuna.logging.set_verbosity(optuna.logging.WARNING)
study = optuna.create_study(direction="maximize", sampler=optuna.samplers.TPESampler(seed=42))
study.optimize(objective, n_trials=40)
print("trials:", len(study.trials), "| best valid AUC:", round(study.best_value, 4))
print("best params:", {k: round(v, 3) if isinstance(v, float) else v for k, v in study.best_params.items()})
print("trees used:", study.best_trial.user_attrs["trees"])

baseline = make_model(learning_rate=0.05, max_depth=4, subsample=0.8, colsample_bytree=0.8)
baseline.fit(X_tr, y_tr, eval_set=[(X_va, y_va)], verbose=False)
tuned = make_model(**study.best_params).fit(X_tr, y_tr, eval_set=[(X_va, y_va)], verbose=False)
for name, m in [("baseline", baseline), ("tuned", tuned)]:
    print(f"{name:8s} test ROC AUC: {roc_auc_score(y_te, m.predict_proba(X_te)[:, 1]):.4f}")
trials: 40 | best valid AUC: 0.8491
best params: {'learning_rate': 0.025, 'max_depth': 2, 'min_child_weight': 14.494, 'subsample': 0.747, 'colsample_bytree': 0.567, 'reg_lambda': 3.933}
trees used: 549
baseline test ROC AUC: 0.8325
tuned    test ROC AUC: 0.8346

Forty trials took about six seconds on 8 CPU cores. The best trial prefers very shallow trees (depth 2), a small learning rate and strong min_child_weight regularisation, using 549 trees. That makes sense: our churn signal is mostly additive, so deep interactions only add noise. The honest result is that tuning improved test ROC AUC from 0.8325 to 0.8346. That is typical. Good defaults plus early stopping get you most of the way, and tuning delivers small, real gains. Be careful with the validation score: the best validation AUC (0.8491) is optimistic, because we picked it out of 40 tries, which is exactly why the final comparison uses the untouched test set. For bigger projects, tuning at scale and AutoML are covered in our hyperparameter optimization in production guide.

Step 4: Prediction intervals with quantile regression

A single number is often not enough. A food delivery app wants to say "25 minutes, almost certainly under 30". XGBoost can train several quantiles in one model with objective="reg:quantileerror" and a list of quantile_alpha values. XGBoost 3.4 reworked how quantile and absolute error objectives compute leaf values, using a smooth approximation instead of a line search.

import numpy as np
import pandas as pd
import xgboost as xgb
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error

# delivery time in minutes: distance, traffic and rush hour make it noisier
rng = np.random.default_rng(11)
n = 5000
X = pd.DataFrame({
    "distance_km": rng.uniform(0.5, 15, n).round(2),
    "items": rng.integers(1, 12, n),
    "rush_hour": rng.integers(0, 2, n),
    "traffic": pd.Categorical(rng.choice(["low", "medium", "high"], n)),
})
noise_scale = 3 + 4 * X.rush_hour + 2 * (X.traffic == "high")
y = (12 + 2.8 * X.distance_km + 0.8 * X["items"] + 6 * X.rush_hour
     + X.traffic.map({"low": 0, "medium": 4, "high": 10}).astype(float)
     + rng.gamma(2.0, noise_scale.to_numpy() / 2))
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=0)

# one model, three quantiles: 10th, 50th (median) and 90th percentile
q = np.array([0.1, 0.5, 0.9])
model = xgb.XGBRegressor(objective="reg:quantileerror", quantile_alpha=q,
                         n_estimators=400, learning_rate=0.05, max_depth=3, random_state=0)
model.fit(X_tr, y_tr)
pred = model.predict(X_te)                       # shape (n_rows, 3)
print("prediction shape:", pred.shape)
low, mid, high = pred[:, 0], pred[:, 1], pred[:, 2]
print(f"median MAE: {mean_absolute_error(y_te, mid):.2f} minutes")
print(f"80% interval coverage: {np.mean((y_te >= low) & (y_te <= high)):.1%}")
print(f"average interval width: {np.mean(high - low):.1f} minutes")

orders = pd.DataFrame({"distance_km": [3.0, 3.0], "items": [4, 4], "rush_hour": [0, 1],
                       "traffic": pd.Categorical(["low", "high"], categories=X.traffic.cat.categories)})
for (_, o), (a, b, c) in zip(orders.iterrows(), model.predict(orders)):
    print(f"3 km, rush_hour={o.rush_hour}, traffic={o.traffic:6s}: {b:5.1f} min (80% range {a:.1f} to {c:.1f})")
prediction shape: (1250, 3)
median MAE: 3.24 minutes
80% interval coverage: 79.6%
average interval width: 10.0 minutes
3 km, rush_hour=0, traffic=low   :  25.0 min (80% range 22.9 to 29.1)
3 km, rush_hour=1, traffic=high  :  46.8 min (80% range 41.4 to 57.3)

The model returns one column per quantile. The median prediction is off by 3.24 minutes on average, and 79.6% of the real test delivery times fall inside the predicted 10th to 90th percentile range, very close to the 80% we asked for. The intervals also adapt to risk: a 3 km order with low traffic outside rush hour gets 25.0 minutes with a range of 22.9 to 29.1, while the same order in rush hour with heavy traffic gets 46.8 minutes and a much wider range of 41.4 to 57.3. Always check coverage on held-out data; too many trees or too deep trees make the intervals too narrow.

Step 5: What changed in XGBoost 3.x for Python users

If you are upgrading old notebooks, run this short check. It shows the defaults and deprecation warnings of the version you have installed.

import warnings
import numpy as np
import pandas as pd
import xgboost as xgb

print("xgboost", xgb.__version__)
print("build:", {k: v for k, v in xgb.build_info().items() if k in ("USE_CUDA", "USE_OPENMP")})

# 1) categorical support is on by default since 3.3 (no enable_categorical=True needed)
X = pd.DataFrame({"color": pd.Categorical(["red", "blue", "green", "blue"] * 50),
                  "size": np.arange(200) % 7})
y = (X.color == "blue").astype(int)
print("enable_categorical default:", xgb.XGBClassifier().get_params()["enable_categorical"])
m = xgb.XGBClassifier(n_estimators=5).fit(X, y)
print("trained on a category column, accuracy:", (m.predict(X) == y).mean())

# 2) deprecations in the 3.3 / 3.4 line
for label, est in [("XGBRFClassifier", lambda: xgb.XGBRFClassifier(n_estimators=10)),
                   ("booster='gblinear'", lambda: xgb.XGBClassifier(booster="gblinear", n_estimators=5))]:
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter("always")
        est().fit(X[["size"]], y)
    msgs = sorted({str(x.message).split(": ")[-1].split(". ")[0].rstrip(".") + "." for x in w})
    print(f"{label}: {len(w)} warning(s)", msgs[:1])

# 3) GPU is a parameter, not a tree method
print("GPU training: XGBClassifier(device='cuda', tree_method='hist')")
xgboost 3.4.1
build: {'USE_CUDA': False, 'USE_OPENMP': True}
enable_categorical default: True
trained on a category column, accuracy: 1.0
XGBRFClassifier: 1 warning(s) ['`XGBRFClassifier` is deprecated and will be removed in a future release.']
booster='gblinear': 1 warning(s) ['`booster=gblinear` is deprecated and support will be removed in a future release.']
GPU training: XGBClassifier(device='cuda', tree_method='hist')
  • Categorical features on by default (3.3): pandas category columns (and Polars Enum columns) are used natively, without one-hot encoding.
  • GPU is a device, not a tree method: tree_method="gpu_hist" was removed; use tree_method="hist", device="cuda".
  • Early stopping and metrics: early_stopping_rounds, eval_metric and callbacks belong in the constructor, not in fit().
  • Deprecated: booster="gblinear" (3.3) and XGBRFClassifier/XGBRFRegressor (3.4). For a random forest, set num_parallel_tree directly.
  • Reproducibility (3.3): each model now has its own random number generator, so training several models with subsample in the same session gives repeatable results.
  • Packaging (3.4): CUDA 13 default wheels, the new xgboost-cu12 package, and xgboost-cpu for CPU-only installs.

Our data in this tutorial uses pandas 3 categories and the new default string dtype; if your older pandas code behaves differently, read our pandas 3 migration guide.

XGBoost vs LightGBM vs scikit-learn HistGradientBoosting

All three are fast histogram-based gradient boosting libraries and they reach similar accuracy on most tables. Choose XGBoost for the most mature ecosystem, built-in SHAP, multi-output and quantile models, strong GPU and distributed (Dask, Spark) support, and portable JSON models. LightGBM is often slightly faster on very large, wide datasets. HistGradientBoostingClassifier in scikit-learn has no extra dependency and fits neatly into pipelines, but has fewer options. If you are unsure, start with XGBoost and early stopping; it is rarely the wrong choice.

Best practices for XGBoost in Python

  • Split into train, validation and test sets. Use validation for early stopping and tuning, and the test set only once at the end.
  • Set a large n_estimators and let early_stopping_rounds pick the number of trees; tune the learning rate instead.
  • Start with max_depth between 3 and 6 and a learning rate between 0.03 and 0.1.
  • Convert string columns to category instead of one-hot encoding them for XGBoost.
  • Save models with save_model("model.json"), not pickle, and record the XGBoost version next to them.
  • Explain predictions with pred_contribs=True before you ship a model that affects people.
  • Fix random_state so experiments are reproducible.

Common errors and fixes

  • "DataFrame.dtypes for data must be int, float, bool or category": you passed string columns. Convert them with df[col].astype("category").
  • "XGBClassifier.fit() got an unexpected keyword argument 'early_stopping_rounds'": move it to the XGBClassifier(...) constructor.
  • "Invalid Input: 'gpu_hist'": replace it with tree_method="hist", device="cuda".
  • "Must have at least 1 validation dataset for early stopping": pass eval_set=[(X_val, y_val)] to fit().
  • Huge install or CUDA errors on a CPU machine: uninstall xgboost and install xgboost-cpu.
  • Predictions differ after loading a model: you loaded a pickle from another version, or you called Booster.predict without iteration_range.

Conclusion

You now have a complete XGBoost workflow in Python for 2026: native categorical features, early stopping, a portable JSON model, global and per-prediction explanations with SHAP, Optuna tuning with an honest test-set check, and quantile regression for prediction intervals. The same pattern works for fraud detection, credit scoring, demand forecasting and any other tabular problem. Swap the generated data for your own CSV, keep the three-way split, and you have a strong baseline in under 50 lines of code.

FAQ

Is XGBoost still worth learning in 2026? Yes. For tabular data, gradient boosted trees remain the strongest and cheapest models in most benchmarks and competitions, and XGBoost had four feature releases between September 2025 and August 2026.

Do I still need enable_categorical=True? Not since XGBoost 3.3; it defaults to True. Your columns must still use the pandas category dtype (or a Polars Enum).

How do I get feature importance from XGBoost? Use model.get_booster().get_score(importance_type="gain") for global importance, and pred_contribs=True for SHAP values per prediction, as in Step 2.

How many trees should I use? Let early stopping decide: set n_estimators high (1,000 to 5,000) and early_stopping_rounds to around 50.

Can XGBoost run on a GPU? Yes. Install the default xgboost wheel and set device="cuda"; the code is otherwise identical.

Tested versions: Python 3.14.10 (CPython), xgboost-cpu 3.4.1, scikit-learn 1.9.1, pandas 3.1.2, numpy 2.5.5, optuna 5.1.0 on Linux x86_64 (8 CPU cores).

Share:
Last updated: December 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices