A
Creating a matrix in Python starts with arranging values into rows and columns. Python can store those rows in nested lists, while NumPy’s ndarray adds numerical operations and shape-aware indexing. I’ll show how to build the rows and convert them to an ndarray. You’ll also see how to choose between element-wise multiplication and a matrix […]
A
A text value may need zeroes added on the left to reach a chosen minimum length. Python’s str.zfill() method returns a string padded with zeroes on the left until it reaches that width. I’ll show how to use zfill() to pad text and explain what happens when it has a leading sign. TL;DR: Pad a […]
A
Working with CSV data in Python starts with getting its rows and columns into a form your code can inspect. pandas is a Python library for working with labeled, table-shaped data. I’ll show you how to install pandas and read a CSV into a table you can inspect. TL;DR Install pandas in the Python environment […]
A
Deleting a file or directory from Python code starts with matching the operation to the path. Python’s standard library provides different operations for files, empty directories, and directories with contents. I’ll show how to remove one file with Path.unlink() and choose the right operation for a directory. TL;DR: Delete a File with Path.unlink Use pathlib.Path.unlink() […]
A
Converting mixed-case text to lowercase gives you a consistent form to display or store. Python’s str.lower() method returns a copy of the string with its letters converted to lowercase. I’ll show how to save that returned value and when to use casefold() to compare strings without regard to case. TL;DR: Use str.lower() Call text.lower() to […]
A
A class may need to allow direct assignment for some values and enforce a rule for others. Encapsulation keeps data and the operations that manage it in one class, and a property can validate values assigned through attribute syntax. I’ll walk through a property that checks a balance and explain how Python marks internal names […]
A
Formatting strings to a minimum width can help align text in Python output. The ljust() and rjust() methods return padded strings, with the original text positioned at the left or right edge. I’ll show how width and fill characters work, and what happens when the requested width is shorter than the string. TL;DR Use str.ljust() […]
A
To read a text file in Python, first choose how your code should receive its contents. The built-in open() gives Python a file object, which can return all the text as one string or provide it one line at a time. I’ll compare reading the whole file with processing it line by line. I’ll also […]
A
To find which values from one Python set do not appear in another, use set difference. It keeps members from the left set that do not occur in the right set. I’ll show how to get a difference without changing the original set and how to update the left set when its contents should change. […]
A
For Python output that should continue on the same line, set what follows each print call. The print() function adds a newline by default, but its end argument can replace that ending. You’ll see how end controls successive calls and how sep separates objects in one print() call. TL;DR: Print Without a Newline in Python […]
A
To organize related values under group keys in Python, you can build a nested dictionary with a for loop. The loop creates a child dictionary for each group, then adds that group’s fields. This article shows how to create a child dictionary for each group and retrieve a value using its group and field keys. […]
A
To find the arithmetic mean of numbers in Python, add the values and divide by their count. Python’s standard library includes statistics.mean(), while sum() and len() can calculate the same result directly. You’ll see both approaches applied to a list and learn how to handle empty input. TL;DR Python has no built-in average() function. Divide […]
A
A square matrix can be analyzed by finding its eigenvalues and eigenvectors. NumPy’s np.linalg.eig returns the eigenvalues and right eigenvectors, with each vector in the column matched to its value by index. This article shows how to compute eigenpairs with NumPy and select a matching value-vector pair. TL;DR Call np.linalg.eig(A) for a square matrix, then […]
A
A message with changing values can use a string template with places for those values. Python’s percent-style formatting uses %s to turn a value into text and insert it at a placeholder. This article shows how to supply values for one or more placeholders and what happens when extra values are supplied. TL;DR: What %s […]
A
A NumPy calculation may need the sine of one angle or a whole set of angles. The np.sin() function computes sine from radian inputs and applies the calculation element by element to arrays. This article shows how to calculate sine and convert degree inputs with np.deg2rad(). TL;DR np.sin() computes sine for angles in radians and […]
A
A Python script that works with image pixels needs to load the image first. OpenCV’s cv2.imread decodes an image file into a NumPy array for processing. You’ll see how to check whether decoding succeeded and how read modes affect the returned array. TL;DR Use cv2.imread(path) to decode an image into a NumPy array, then check […]
A
Turning JSON data into rows and columns is the task when you want to work with it as a pandas table. pandas.read_json() parses JSON input into a pandas object, usually a DataFrame. This article shows how to match orient to the JSON shape and read newline-delimited JSON in chunks. TL;DR Use pandas.read_json() to turn JSON […]
A
Earlier this year, attackers slipped malicious code into LiteLLM, a widely used Python package. By the time PyPI quarantined the compromised versions, they had been downloaded more than 119,000 times in just two hours and 32 minutes. PyPI estimated that 40% to 50% of LiteLLM installations were unpinned, meaning they automatically fetched the latest release. […]
A
To convert a Python string to a list, use the conversion that matches the string. Python’s list() turns each character into an item, while split() divides text at whitespace or a delimiter. I’ll show how to choose a conversion for the input format and check how empty fields appear. TL;DR Use the conversion that matches […]
A
Several characters in a Python string may need different changes before the text is used elsewhere. str.translate() applies a table of character rules and returns a new string. This article shows how to build that table with str.maketrans() and when a character table fits better than replace(). TL;DR: Use str.translate() for character maps Build a […]
A
When you use a complex number in a Python calculation, you need to know how to represent it and work with its two components. Python’s built-in complex type stores those components together, with j marking the imaginary unit. This guide shows how to calculate with complex values and convert them between rectangular and polar form. […]
A
A text value may need to match one expected ending or one of several alternatives. Python’s str.endswith() method checks whether a string ends with the supplied suffix and returns True or False. This article explains how to pass several suffixes as a tuple and how start and end limit the checked range. TL;DR Call str.endswith(suffix) […]
A
Comparing two coordinate points starts with choosing what kind of distance the calculation should represent. In Python, math.dist measures straight-line Euclidean distance for points with matching dimensions. This article demonstrates the calculation and checks it against a manual result. It also shows when array libraries or a different distance measure fit the task. TL;DR: Calculate […]
A
You’ve filled out a form, signed it, and saved it as a PDF. Then the recipient asks you to fax it. An online fax service lets you send the file from your browser or phone and check whether it went through. If you’re starting with paper, some mobile fax apps can scan the pages and […]
A
To turn a sentence into separate words, you can split its text at whitespace. Python’s str.split() returns the pieces as a list of strings and can also use a separator you specify. I’ll show how to choose a separator and limit how many splits Python makes. TL;DR: Split a String Into a Python List Call […]
A
Saving an image in Python starts with choosing a filename and destination. cv2.imwrite() encodes an image array using the filename extension and writes it to a file. This article shows how to save an array with cv2.imwrite() and where a relative path points. TL;DR Use cv2.imwrite(filename, image) to encode an image array using the filename […]
A
For an image-classification task, CIFAR-10 provides labeled examples for training and evaluation. It contains 60,000 small RGB images divided among ten classes. This article explains how Python exposes CIFAR-10 data and how to inspect image and label shapes before preprocessing. TL;DR CIFAR-10 is a labeled image dataset with 60,000 small RGB images, and Python libraries […]
A
A condition can tell you whether a Python list has items. Python conditions use an object’s truth value, and empty lists are false. This article shows how to check whether a list is empty and how to handle None when the variable may have no list value. TL;DR Use if not items: to handle an […]
A
Estimating a parameter means using observations to choose a value for it. Maximum a posteriori (MAP) estimation combines those observations with a prior, information about the parameter before the data, and selects the value best supported by both. I’ll show how to calculate the estimate in Python and check how changing the prior changes its […]
A
Saving a pandas DataFrame as an Excel workbook starts with DataFrame.to_excel(). It writes the table to a worksheet, where you can choose a name and whether the row index appears. I’ll show how to export a single worksheet and write multiple DataFrames to one workbook. TL;DR Call DataFrame.to_excel() with a filename, then set index=False when […]