Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Access Array Elements
course content

Course Content

NumPy in a Nutshell

Access Array ElementsAccess Array Elements

In both lists and arrays, elements are accessed using square brackets. Let's review the distinction between indexing and slicing:

  • To retrieve a single element, you simply need to specify the index of that element in square brackets (start counting from 0).
  • If you want to obtain a sequence from the original array, you should use slices.

We'll start with simple indexing. Let's have a look at the following image:

Example

Let's see how it works with examples.

Get the first element from the following array:

Retrieve the second element from the following array:

Retrieve the third and fourth elements from the following array and then add them together:

Now, it's time to explore slicing. First, let's examine the syntax of slicing: array[start:end:step], where:

  • start is the index from which slicing begins;
  • end is the index where slicing stops (note that this index is not included);
  • step is the parameter that specifies the intervals between the indices.

Let's have a look at the following image:

Example

Omitting start, end and step

As you can see, we can often omit the start, end, step or even all of them at the same time. step, for example, can be omitted when we want it to be equal to 1. start and end can be omitted in the following scenarios:

  1. Omitting start:
    • slicing from the first element (step is positive);
    • slicing from the last element (step is negative).
  2. Omitting end:
    • slicing to the last element inclusive (step is positive);
    • slicing to the first element inclusive (step is negative).

In the example above, a[2:4] has the step equal to 1. a[-2:] goes from the second to last element to the end of the array with step equal to 1. a[::2] goes from the first element to the end of the array with step equal to 2.

It's time to practice.

Task

Retrieve the first and last elements from the following array [13, 99, 11, 23, 5, 41] and then multiply them. Please use positive indexing.

Everything was clear?

Section 3. Chapter 1
Switch to desktop for real-world practiceContinue from where you are using one of the options below
some-alt