Why Are Membership Tests So Fast for range() in Python?
In Python, range() is most commonly used in for loops to iterate over a known range of numbers. But that’s not all it can do! There are other interesting uses of range(). For example, you can pick out elements of a range or check whether a given number belongs to a range of numbers. The latter operation is known as a membership test. Python’s range() objects support most of the operations that you’ve come to expect from lists. For example, […]
Read moreJinja Templating
Templates are an essential ingredient in full-stack web development. With Jinja, you can build rich templates that power the front end of your Python web applications. Jinja is a text templating language. It allows you to process a block of text, insert values from a context dictionary, control how the text flows using conditionals and loops, modify inserted data with filters, and compose different templates together using inheritance and inclusion. In this video course, you’ll learn how to: Install the […]
Read moreHow to Flatten a List of Lists in Python
Sometimes, when you’re working with data, you may have the data as a list of nested lists. A common operation is to flatten this data into a one-dimensional list in Python. Flattening a list involves converting a multidimensional list, such as a matrix, into a one-dimensional list. To better illustrate what it means to flatten a list, say that you have the following matrix of numeric values: >>> >>> matrix = [ … [9, 3, 8, 3], … [4, 5, […]
Read morePython’s Self Type: How to Annotate Methods That Return self
Have you ever found yourself lost in a big repository of Python code, struggling to keep track of the intended types of variables? Without the proper use of type hints and annotations, uncovering variable types can become a tedious and time-consuming task. Perhaps you’re an avid user of type hints but aren’t sure how to annotate methods that return self or other instances of the class itself. That’s the issue that you’ll tackle in this tutorial. First, though, you’ll need […]
Read moreRecursion in Python
If you’re familiar with functions in Python, then you know that it’s quite common for one function to call another. In Python, it’s also possible for a function to call itself! A function that calls itself is said to be recursive, and the technique of employing a recursive function is called recursion. It may seem peculiar for a function to call itself, but many types of programming problems are best expressed recursively. When you bump up against such a problem, […]
Read more