With cleveref and its macro \crefname, you can create a custom counter and assign a label to it--I have added python code for demonstration. Then, with minipage, you could create some space at the right-hand side of the code for a number; I have done it with minipage, which by default aligns a number in the middle.
In the code below, I also suggest a custom environment pythoncode with an optional parameter if for some reason you would like to increase/decrease indentation. Of course, you could parameterise any other option of the environment.

\documentclass{article}
% \usepackage[utf8]{inputenc}
\usepackage{geometry}
\geometry{paper=a4paper, left=24mm, right=23mm, top=20mm, bottom=20mm}
\usepackage{blindtext}
\usepackage{enumerate}
\usepackage{listings}
\lstnewenvironment{pythoncode}[1][.1]{%
\lstset{
basicstyle=\ttfamily\footnotesize,
xleftmargin=#1\textwidth,
language=Python,
}}{}
\usepackage[noabbrev]{cleveref}
%%% New counter controlling python code numbers
\newcounter{lst}
\renewcommand*{\thelst}{(\arabic{lst})} % Format the counter (currently (<number>)
\crefname{lst}{python code}{python codes} % Adds a label when referencing
\AtBeginEnvironment{minipage}{\noindent} % Removes indentation at the beginning of each minipage
\begin{document}
\blindtext
\begin{minipage}{\dimexpr\textwidth-3em}%
\refstepcounter{lst}\label{lst:a}%
\begin{pythoncode}
def generate_grid(data, basemap, delta=1):
grid = {
'lon': np.arange(-180, 180, delta),
'lat': np.arange(-89.9,89.9, delta)
}
grid["x"], grid["y"] = np.meshgrid(grid["lon"], grid["lat"])
grid["x"], grid["y"] = basemap(grid["x"], grid["y"])
return grid
\end{pythoncode}%
\end{minipage}{\raggedleft\thelst\par}
\blindtext
\begin{minipage}{\dimexpr\textwidth-3em}
\refstepcounter{lst}\label{lst:b}%
\begin{pythoncode}
def foo(x):
return x**2
\end{pythoncode}
\end{minipage}{\raggedleft\thelst\par}
\Cref{lst:a} and \cref{lst:b}.
\end{document}