Inspect a live Python function, call a custom alias, then read a public Python documentation page and add it as a notebook note. Connect ChatGPT or an API provider for the AI questions. The web tools contact the public page only when you run the relevant question; each returned excerpt includes its source URL. Review an inserted note before saving this notebook.
Inspect Python and read public documentation
Inspect a live Python function, call a custom alias, then read a public Python documentation page and add it as a notebook note. Connect ChatGPT or an API provider for the AI questions. The web tools contact the public page only when you run the relevant question; each returned excerpt includes its source URL. Review an inserted note before saving this notebook.
from nbinlineai.tools import inspect_python, read_url, tools_markdown, url_to_note
defcalculate_average(values: list[int]) ->float:
"""Return the arithmetic mean of a nonempty list of integers."""returnsum(values) /len(values)
average_alias = calculate_average
print("Python and web tools imported.")
This module provides functions for calculating mathematical statistics of numeric (Real-valued) data.
The module is not intended to be a competitor to third-party libraries such as NumPy, SciPy, or proprietary full-featured statistics packages aimed at professional statisticians such as Minitab, SAS and Matlab. It is aimed at the level of graphing and scientific calculators.
Unless explicitly noted, these functions support int, float, Decimal and Fraction. Behaviour with other types (whether in the numeric tower or not) is currently unsupported. Collections with a mix of types are also undefined and implementation-dependent. If your input data consists of mixed types, you may be able to use map() to ensure a consistent result, for example: map(float, input_data).
Some datasets use NaN (not a number) values to represent missing data. Since NaNs have unusual comparison semantics, they cause surprising or undefined behaviors in the statistics functions that sort data or that count occurrences. The functions affected are median(), median_low(), median_high(), median_grouped(), mode(), multimode(), and quantiles(). The NaN values should be stripped before calling these functions:
>>> from statistics import median
>>> from math import isnan
>>> from itertools import filterfalse
>>> data = [20.7, float('NaN'),19.2, 18.3, float('NaN'), 14.4]
>>> sorted(data) # This has surprising behavior
[20.7, nan, 14.4, 18.3, 19.2, nan]
>>> median(data) # This result is unexpected
16.35
>>> sum(map(isnan, data)) # Number of missing values
2
>>> clean = list(filterfalse(isnan, data)) # Strip NaN values
>>> clean
[20.7, 19.2, 18.3, 14.4]
>>> sorted(clean) # Sorting now works as expected
[14.4, 18.3, 19.2, 20.7]
>>> median(clean) # This result is now well defined
18.75
Averages and measures of central location¶
These functions calculate an average or typical value from a population or sample.
mean()
Arithmetic mean (“average”) of data.
fmean()
Fast, floating-point arithmetic mean, with optional weighting.
geometric_mean()
Geometric mean of data.
harmonic_mean()
Harmonic mean of data.
kde()
Estimate the probability density distribution of the data.
kde_random()
Random sampling from the PDF generated by kde().
median()
Median (middle value) of data.
median_low()
Low median of data.
median_high()
High median of data.
median_grouped()
Median (50th percentile) of grouped data.
mode()
Single mode (most common value) of discrete or nominal data.
multimode()
List of modes (most common values) of discrete or nominal data.
quantiles()
Divide data into intervals with equal probability.
Measures of spread¶
These functions calculate a measure of how much the population or sample tends to deviate from the typical or average values.
pstdev()
Population standard deviation of data.
pvariance()
Population variance of data.
stdev()
Sample standard deviation of data.
variance()
Sample variance of data.
Statistics for relations between two inputs¶
These functions calculate statistics regarding relations between two inputs.
covariance()
Sample covariance for two variables.
correlation()
Pearson and Spearman’s correlation coefficients.
linear_regression()
Slope and intercept for simple linear regression.
Function details¶
Note: The functions do not require the data given to them to be sorted. However, for reading convenience, most of the examples show sorted sequences.
statistics.mean(data)¶
Return the sample arithmetic mean of data which can be a sequence or iterable.
The arithmetic mean is the sum of the data divided by the number of data points. It is commonly called “the average”, although it is only one of many different mathematical averages. It is a measure of the central location of the data.
If data is empty, StatisticsError will be raised.
Some examples of use:
>>> mean([1, 2, 3, 4, 4])
2.8
>>> mean([-1.0, 2.5, 3.25, 5.75])
2.625
>>> from fractions import Fraction as F
>>> mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)])
Fraction(13, 21)
>>> from decimal import Decimal as D
>>> mean([D("0.5"), D("0.75"), D("0.625"), D("0.375")])
Decimal('0.5625')
Note
The mean is strongly affected by outliers and is not necessarily a typical example of the data points. For a more robust, although less efficient, measure of central tendency, see median().
The sample mean gives an unbiased estimate of the true population mean, so that when taken on average over all the possible samples, mean(sample) converges on the true mean of the entire population. If data represents the entire population rather than a sample, then mean(data) is equivalent to calculating the true population mean μ.
statistics.fmean(data, weights=None)¶
Convert data to floats and compute the arithmetic mean.
This runs faster than the mean() function and it always returns a float. The data may be a sequence or iterable. If the input dataset is empty, raises a StatisticsError.
>>> fmean([3.5, 4.0, 5.25])
4.25
Optional weighting is supported. For example, a professor assigns a grade for a course by weighting quizzes at 20%, homework at 20%, a midterm exam at 30%, and a final exam at 30%:
If weights is supplied, it must be the same length as the data or a ValueError will be raised.
Added in version 3.8.
Changed in version 3.11: Added support for weights.
statistics.geometric_mean(data)¶
Convert data to floats and compute the geometric mean.
The geometric mean indicates the central tendency or typical value of the data using the product of the values (as opposed to the arithmetic mean which uses their sum).
Raises a StatisticsError if the input dataset is empty, if it contains a zero, or if it contains a negative value. The data may be a sequence or iterable.
No special efforts are made to achieve exact results. (However, this may change in the future.)
Return the harmonic mean of data, a sequence or iterable of real-valued numbers. If weights is omitted or None, then equal weighting is assumed.
The harmonic mean is the reciprocal of the arithmetic mean() of the reciprocals of the data. For example, the harmonic mean of three values a, b and c will be equivalent to 3/(1/a + 1/b + 1/c). If one of the values is zero, the result will be zero.
The harmonic mean is a type of average, a measure of the central location of the data. It is often appropriate when averaging ratios or rates, for example speeds.
Suppose a car travels 10 km at 40 km/hr, then another 10 km at 60 km/hr. What is the average speed?
>>> harmonic_mean([40, 60])
48.0
Suppose a car travels 40 km/hr for 5 km, and when traffic clears, speeds-up to 60 km/hr for the remaining 30 km of the journey. What is the average speed?
Available tools (delete any line you do not want to offer):
- &`inspect_python` — Inspect a live Python name's help, signature, or available source.
- &`read_url` — Read a public web page as bounded, sanitized Markdown with its source URL.
- &`url_to_note` — Fetch a public page and insert its bounded Markdown as a notebook note.
- &`average_alias` — Return the arithmetic mean of a nonempty list of integers.
Inspect a live Python definition
Use a public name from the kernel. The section argument accepts help, signature, or source. Private attributes and expressions such as calculate_average() are rejected.
Call &inspect_python with name="calculate_average" and section="signature". Then call it with the same name and section="source". Explain the function using what the tool actually returned.
calculate_average(values: list[int]) -> float returns the arithmetic mean of a nonempty list of integers, computed as sum(values) / len(values).
Observed live tool calls for the answer above (actual subscription events; private fields shortened).
‘Source for calculate_average:\ndef calculate_average(values: list[int]) -> float:\n “”“Return the arithmetic mean of a nonempty list of integers.”“”\n return sum(values) / len(values)\n’
Add one custom alias explicitly
The setup cell binds average_alias in the kernel. tools_markdown(..., custom={"average_alias": average_alias}) only prints its reference. Put &`average_alias` in an ordinary Markdown declaration above the question, or in an earlier AI question, to offer the alias to lower questions. The import or binding must still exist in the live kernel.
Call &average_alias with values=[3, 7, 8] and report the returned mean. Do not infer the result without the tool call.
average_alias([3, 7, 8]) returned 6.0.
Observed live tool calls for the answer above (actual subscription events; private fields shortened).
Tool
Result state
Submitted arguments
Observed result
average_alias
completed
{“values”:[3,7,8]}
6.0
Read a public Python documentation page
The next tool performs an outbound HTTP(S) request. It rejects local/private network hosts, limits redirects, time, size, and content type, and returns a short source-attributed Markdown excerpt. A remote page is untrusted context; verify important claims at the cited URL.
Call &read_url with url="https://docs.python.org/3/library/statistics.html". Give one fact you can see in the returned text and include the source URL.
The statistics module provides functions for calculating mathematical statistics of numeric data. Source: https://docs.python.org/3/library/statistics.html
Observed live tool calls for the answer above (actual subscription events; private fields shortened).
"Source: https://docs.python.org/3/library/statistics.html\n\nstatistics — Mathematical statistics functions — Python 3.14.7 documentation\n\n### Navigation\n\n- index\n- modules |\n- next |\n- previous |\n-\n- Python »\n-\n\n-\n- 3.14.7 Documentation »\n- The Python standard library »\n- Numeric and Mathematical Modules »\n- statistics — Mathematical statistics functions\n-\n\n |\n- Theme Auto Light Dark |\n\n# statistics — Mathematical statistics functions¶\n\nAdded in version 3.4.\n\nSource code: Lib/statistics.py\n\nThis module provides functions for calculating mathematical statistics of numeric (Real-valued) data.\n\nThe module is not intended to be a competitor to thir
Keep a public page as a notebook note
The next tool fetches the same public page and inserts a Markdown note after the setup cell. Review the inserted content and use JupyterLab Save to persist it. If the network is unavailable, keep working in the notebook and retry later.
Call &url_to_note with url="https://docs.python.org/3/library/statistics.html" and after_cell_id="web-tool-setup". Tell me that the note appeared in the current notebook and remind me to save it.
The note appeared in the current notebook. Review it, then use JupyterLab Save to persist it.
Observed live tool calls for the answer above (actual subscription events; private fields shortened).
Inserted Markdown cell ed417acb-2fce-4f69-82cf-7aae63898a53 in the live notebook model (not saved to disk).
Teaching check
Which actions read local live state, which read public web content, and which insert a new Markdown cell? Keep ordinary Markdown declarations selective. Every lower AI question inherits the tools they name. Only current-question $ references read live variable values.