Change index in array python

I am trying this simple code to search in an array and replace the elements that are greater than 1 to 1:

import numpy as np

j = np.array([[1],[3],[1],[0],[9]])

for x in j:
    if abs(x) > 1 :
        j[x] = 1

But I get such errors:

IndexError: index 9 is out of bounds for axis 0 with size 5

asked Mar 2, 2019 at 21:06

WDRWDR

1,0531 gold badge13 silver badges37 bronze badges

2

If all you're doing is making all values if absolute(j[i]) is greater than 1 to 1 then numpy has this capability built in and it's so simple it can be done in one line and more efficient than any python loop:

j[np.absolute(j) > 1] = 1

To show you how this would work:

#made 3 a negitive value to prove absolute works.
j = np.array([[1],[-3],[1],[0],[9]])

j[np.absolute(j) > 1] = 1

j is now:

[[1]
 [1]
 [1]
 [0]
 [1]]

answered Mar 2, 2019 at 21:24

Change index in array python

JabJab

25.7k21 gold badges74 silver badges113 bronze badges

When you traverse an array in a for loop you are actually accessing the elements, not the index. After all, you are comparing x against 1. You can retrieve the index in many ways, one of the common ones is to use enumerate, like so:

import numpy as np

j = np.array([[1],[3],[1],[0],[9]])

for i,x in enumerate(j):    # i is the index, x is the value
    if abs(x) > 1 :
        j[i] = 1

answered Mar 2, 2019 at 21:17

salsal

3,4051 gold badge9 silver badges21 bronze badges

Try to change the for loop using enumerate to :

import numpy as np

j = np.array([[1],[3],[1],[0],[9]])

for i,x in enumerate(j):
    if abs(x) > 1 :
        j[i] = 1

answered Mar 2, 2019 at 21:19

Change index in array python

as you see in your error output

IndexError: index 9 is out of bounds for axis 0 with size 5

you are trying to update a value at index 9 but your array is of size 5. which clearly means you are not using the index of array but actually the value at index.

enumerate your array and run a loop with both index & value

for i,x in  enumerate(j):
    if abs(x) > 1 :
        j[i] = 1

answered Mar 2, 2019 at 21:19

Change index in array python

Are you trying to make a two dimensional array? You have your elements in brackets within brackets "[[1],[3],[1],[0],[9]]" .... also, you're iterating over values, not indices: x is an array value "[3]" not an index "1".

Change to:

import numpy as np

j = np.array([1,3,1,0,9])

# Keep track of index starting at 0
i = 0
for x in j:
    if abs(x) > 1 :
        # change value at index i
        j[i] = 1
    # increment index
    i += 1

answered Mar 2, 2019 at 21:25

You may want to replace the for statement with this:

for x in range(len(j))

answered Mar 2, 2019 at 21:39

Python arrays are homogenous data structure. They are used to store multiple items but allow only the same type of data. They are available in Python by importing the array module.

Lists, a built-in type in Python, are also capable of storing multiple values. But they are different from arrays because they are not bound to any specific type.

So, to summarize, arrays are not fundamental type, but lists are internal to Python. An array accepts values of one kind while lists are independent of the data type.

Python List

In this tutorial, you’ll get to know how to create an array, add/update, index, remove, and slice.

Python Arrays – A Beginners Guide

Contents

  • 1 Arrays in Python
    • 1.1 What is Array in Python?
    • 1.2 Array Illustration
  • 2 Declare Array in Python
    • 2.1 Syntax
    • 2.2 Example
  • 3 Array Operations
    • 3.1 Indexing an array
    • 3.2 Slicing arrays
    • 3.3 Add/Update an array
    • 3.4 Remove array elements
    • 3.5 Reverse array

Arrays in Python

What is Array in Python?

An array is a container used to contain a fixed number of items. But, there is an exception that values should be of the same type.

The following are two terms often used with arrays.

  • Array element – Every value in an array represents an element.
  • Array index – Every element has some position in the array known as the index.

Let’s now see how Python represents an array.

Array Illustration

The array is made up of multiple parts. And each section of the array is an element. We can access all the values by specifying the corresponding integer index.

The first element starts at index 0 and so on. At 9th index, the 10th item would appear. Check the below graphical illustration.

Change index in array python

Declare Array in Python

You have first to import the array module in your Python script. After that, declare the array variable as per the below syntax.

Syntax

# How to declare an array variable in Python
from array import *
array_var = array(TypeCode, [Initializers]

In the above statements, “array_var” is the name of the array variable. And we’ve used the array() function which takes two parameters. “TypeCode” is the type of array whereas “Initializers” are the values to set in the array.

The argument “TypeCode” can be any value from the below chart.

Change index in array python

In the above diagram, we’ve listed down all possible type codes for Python and C Types. But we’ll only be using the Python Types “i” for integers and “d” for floats here in our examples.

Also, note that there is one Unicode type shown in the chart. Its support ended since Python version 3.3. So, it is best not to use it in your programs.

Example

Let’s consider a simple case to create an array of 10 integers.

import array as ar

# Create an array of 10 integers using range()
array_var = ar.array('i', range(10))
print("Type of array_var is:", type(array_var))

# Print the values generated by range() function
print("The array will include: ", list(range(10)))

We first imported the array module and then used the range() function to produce ten integers. We’ve also printed the numbers that our array variable would hold.

Python Range

Here is the outcome of the above program.

Type of array_var is: <class 'array.array'>
The array will include: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In the next sections, we’ll cover all actions that can be performed using arrays.

Array Operations

Indexing an array

We can use indices to retrieve elements of an array. See the below example:

import array as ar

# Create an array of 10 integers using range()
array_var = ar.array('i', range(10))

# Print array values using indices
print("1st array element is {} at index 0.".format(array_var[0]))
print("2nd array element is {} at index 1.".format(array_var[1]))
print("Last array element is {} at index 9.".format(array_var[9]))
print("Second array element from the tail end is {}.".format(array_var[-2]))

Arrays have their first element stored at the zeroth index. Also, you can see that if we use -ve index, then it gives us elements from the tail end.

The output is:

1st array element is 0 at index 0.
2nd array element is 1 at index 1.
Last array element is 9 at index 9.
Second array element from the tail end is 8.

Slicing arrays

The slice operator “:” is commonly used to slice strings and lists. However, it does work for the arrays also. Let’s see with the help of examples.

from array import *

# Create an array from a list of integers
intger_list = [10, 14, 8, 34, 23, 67, 47, 22]
intger_array = array('i', intger_list)

# Slice the given array in different situations
print("Slice array from 2nd to 6th index: {}".format(intger_array[2:6]))
print("Slice last 3 elements of array: {}".format(intger_array[:-3]))
print("Slice first 3 elements from array: {}".format(intger_array[3:]))
print("Slice a copy of entire array: {}".format(intger_array[:]))

When you execute the above script, it produces the following output:

Slice array from 2nd to 6th index: array('i', [8, 34, 23, 67])
Slice last 3 elements of array: array('i', [10, 14, 8, 34, 23])
Slice first 3 elements from array: array('i', [34, 23, 67, 47, 22])
Slice a copy of entire array: array('i', [10, 14, 8, 34, 23, 67, 47, 22])

The following two points, you should note down:

  • When you pass both the left and right operands to the slice operator, then they act as the indexes.
  • If you take one of them whether the left or right one, then it represents the no. of elements.

Add/Update an array

We can make changes to an array in different ways. Some of these are as follows:

  • Assignment operator to change or update an array
  • Append() method to add one element
  • Extend() method to add multiple items

We’ll now understand each of these approaches with the help of examples.

Let’s begin by using the assignment operator to update an existing array variable.

from array import *

# Create an array from a list of integers
num_array = array('i', range(1, 10))
print("num_array before update: {}".format(num_array))

# Update the elements at zeroth index
index = 0
num_array[index] = -1
print("num_array after update 1: {}".format(num_array))

# Update the range of elements, say from 2-7
num_array[2:7] = array('i', range(22, 27))
print("num_array after update 2: {}".format(num_array))

The output is:

num_array before update: array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9])
num_array after update 1: array('i', [-1, 2, 3, 4, 5, 6, 7, 8, 9])
num_array after update 2: array('i', [-1, 2, 22, 23, 24, 25, 26, 8, 9])

Now, we’ll apply the append() and extend() methods on a given array. These work the same for lists in Python. See the tutorial below.

Difference Between List Append() and Extend()

from array import *

# Create an array from a list of integers
num_array = array('i', range(1, 10))
print("num_array before append()/extend(): {}".format(num_array))

# Add one elements using the append() method
num_array.append(99)
print("num_array after applying append(): {}".format(num_array))

# Add multiple elements using extend() methods
num_array.extend(range(20, 25)) 
print("num_array after applying extend(): {}".format(num_array))

This program yields the following:

num_array before append()/extend(): array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9])
num_array after applying append(): array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 99])
num_array after applying extend(): array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 99, 20, 21, 22, 23, 24])

The point to note is that both append() or extend() adds elements to the end.

The next tip is an interesting one. We can join two or more arrays using the “+” operator.

Python Operator

from array import *

# Declare two arrays using Python range()
# One contains -ve integers and 2nd +ve values.
num_array1 = array('i', range(-5, 0))
num_array2 = array('i', range(0, 5))

# Printing arrays before joining
print("num_array1 before joining: {}".format(num_array1))
print("num_array2 before joining: {}".format(num_array2))

# Now, concatenate the two arrays
num_array = num_array1 + num_array2

print("num_array after joining num_array1 and num_array2: {}".format(num_array))

The above script shows the following result after execution:

num_array1 before joining: array('i', [-5, -4, -3, -2, -1])
num_array2 before joining: array('i', [0, 1, 2, 3, 4])
num_array after joining num_array1 and num_array2: array('i', [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4])

Remove array elements

There are multiple ways that we can follow to remove elements from an array. Here are these:

  • Python del operator
  • Remove() method
  • Pop() method

Let’s first check how Python del works to delete arrays members.

from array import *

# Declare an array of 10 floats
num_array = array('f', range(0, 10))

# Printing the array before deletion of elements
print("num_array before deletion: {}".format(num_array))

# Delete the first element of array
del num_array[0]
print("num_array after removing first element: {}".format(num_array))

# Delete the last element
del num_array[len(num_array)-1]
print("num_array after removing the last element: {}".format(num_array))

# Remove the entire array in one go
del num_array

# Printing a deleted array would raise the NameError
print("num_array after removing first element: {}".format(num_array))

The output is as follows:

num_array before deletion: array('f', [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0])
num_array after removing first element: array('f', [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0])
num_array after removing the last element: array('f', [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0])
print("num_array after removing first element: {}".format(num_array))
-->NameError: name 'num_array' is not defined

Now, let’s try to utilize the remove() and pop() methods. The former removes the given value from the array whereas the latter deletes the item at a specified index.

from array import *

# Declare an array of 8 numbers
num_array = array('i', range(11, 19))

# Printing the array before deletion of elements
print("num_array before deletion: {}".format(num_array))

# Remove 11 from the array
num_array.remove(11)
print("Array.remove() to remove 11: {}".format(num_array))

# Delete the last element
num_array.pop(len(num_array)-1)
print("Array.pop() to remove last element: {}".format(num_array))

After running this code, we get the below result:

num_array before deletion: array('i', [11, 12, 13, 14, 15, 16, 17, 18])
Array.remove() to remove 11: array('i', [12, 13, 14, 15, 16, 17, 18])
Array.pop() to remove last element: array('i', [12, 13, 14, 15, 16, 17])

Reverse array

The last but not the least is how we can reverse the elements of an array in Python. There can be many approaches to this. However, we’ll take the following two:

  • Slice operator in Python
  • Python List comprehension

Check out the below sample code to invert the element in a given array.

from array import *

# Declare an array of 8 numbers
num_array = array('i', range(11, 19))

# Printing the original array
print("num_array before the reverse: {}".format(num_array))

# Reverse the array using Python's slice operator
print("Reverse num_array using slice operator: {}".format(num_array[::-1]))

# Reverse the array using List comprehension
print("Reverse num_array using List comprehension: {}".format(array('i', [num_array[n] for n in range(len(num_array) - 1, -1, -1)])))

The above code produces the following output after running:

num_array before the reverse: array('i', [11, 12, 13, 14, 15, 16, 17, 18])
Reverse num_array using slice operator: array('i', [18, 17, 16, 15, 14, 13, 12, 11])
Reverse num_array using List comprehension: array('i', [18, 17, 16, 15, 14, 13, 12, 11])

Now, we are mentioning a bonus method to reverse the array using the reversed() call. This function inverts the elements and returns a “list_reverseiterator” type object.

Python Reversed()

"""
 Example:
  Applying Python Reversed() on an array
"""
from array import *

def print_Result(iter, orig):
    print("##########")
    print("Original: ", orig)
    print("Reversed: ", end="")
    for it in iter:
        print(it, end=' ')
    print("\n##########")

def reverse_Array(in_array):
    result = reversed(in_array)
    print_Result(result, in_array)

# Declare an array of 8 numbers
in_array = array('i', range(11, 19))

reverse_Array(in_array)

Here is the output of the above example.

##########
Original: array('i', [11, 12, 13, 14, 15, 16, 17, 18])
Reversed: 18 17 16 15 14 13 12 11 
##########

We hope that after wrapping up this tutorial, you should feel comfortable in using Python arrays. However, you may practice more with examples to gain confidence.

Also, to learn Python from scratch to depth, do read our step by step Python tutorial.

Can you change the index of an array?

To change the position of an element in an array: Use the splice() method to insert the element at the new index in the array. The splice method changes the original array by removing or replacing existing elements, or adding new elements at a specific index.

How do you change the index value in Python?

To change the index values we need to use the set_index method which is available in pandas allows specifying the indexes. where, inplace parameter accepts True or False, which specifies that change in index is permanent or temporary. True indicates that change is Permanent.

How do you change a value in an array in Python?

Changing Multiple Array Elements In Python, it is also possible to change multiple elements in an array at once. To do this, you will need to make use of the slice operator and assign the sliced values a new array to replace them.

Can you modify arrays in Python?

We can make changes to an array in different ways. Some of these are as follows: Assignment operator to change or update an array. Append() method to add one element.