Python 3 latest code crumbs

Return the last element of a Python list

Return the last element of a Python list

Apr 5, 2022 by erik

Finish the function so it returns the last element of the given list. You may assume the list is not empty....

Demonstration of how a Python range works

Demonstration of how a Python range works

Mar 6, 2022 by erik

A range is an iterable object, and this object can return an iterator that keeps track of its current state. Suppose we create a range with the call range(3). This returns an object of type range with our requested settings....

Python for-loop using range with start and stop

Python for-loop using range with start and stop

Mar 6, 2022 by erik

We don't always want to start counting at zero, and that's why we can also call range with both a start and stop value. A call to range(2, 5) will return the values 2, 3, and 4....

Python for-loop with range (with one argument)

Python for-loop with range (with one argument)

Mar 6, 2022 by erik

If we call Python's range with one argument, that argument is the stop value. In this case, range will start counting at 0 until it reaches the stop value. For example, if we call range(5), the created range object will...

Creating a Python iterator

Creating a Python iterator

Mar 1, 2022 by erik

There’s no magic to creating your own iterator. I’ll demonstrate with a simple iterator class that returns even numbers. As we’ve learned, we need to implement __iter__ and __next__. We’ll do this in one single class, to keep things simple....

Python ZeroDivisionError: Handling Division By Zero

Python ZeroDivisionError: Handling Division By Zero

Mar 1, 2022 by erik

As you hopefully know, we can't divide by the number zero. If we do so anyway, Python will throw an exception called ZeroDivisionError, which is a subclass of ArithmeticError. When can catch this exception with a Python try except block....