Array manipulation and element retrieval is a common task among any programming language, and luckily Python has some useful syntax for easily retrieving elements from various positions in the list.
One common use case is to retrieve N elements from the end of a list/array, which we'll show how to do here.
Background: Python Array Syntax
In Python, you can retrieve elements using similar syntax as in many other languages, using brackets (
) and an index. However, this syntax can be extended to optionally specify both a starting and ending index. By providing both indexes, you can retrieve a range of elements:
1, 2, 3, 4, 5, 6] arr[2:4] [3, 4]arr = [
What if you omitted the ending index? In that case, Python will automatically assume you want to retrieve elements from the starting index to the end of the list.
1, 2, 3, 4, 5, 6] arr[2:] [3, 4, 5, 6]arr = [
The indexes can also be negative, which specifies the element index from the end of the list.
1, 2, 3, 4, 5, 6] arr[-2] 5arr = [
Last N Elements
Using this knowledge we have of accessing multiple elements from the end of the list, we can then figure out how to access the last N elements. To do so, simply use the syntax
N is the number of elements you want to access:
1, 2, 3, 4, 5, 6] arr[-2:] [5, 6]arr = [
We can also use variables to specify how many elements to retrieve:
1, 2, 3, 4, 5, 6] n = 3 arr[-n:] [4, 5, 6]arr = [
Using either of these methods you can retrieve the last N elements of a list/array in Python.
Building Your First Convolutional Neural Network With Keras# python# artificial intelligence# machine learning# tensorflow
Most resources start with pristine datasets, start at importing and finish at validation. There's much more to know. Why was a class predicted? Where was...