Python

Python Array Example

Hello in this tutorial, we will see how to use arrays in python programming.

1. Introduction

Array module in python is used to create an array with constraints on the data types. In this tutorial, we will focus on this module to store a collection of integer values and play around with it.

1.1 Setting up Python

If someone needs to go through the Python installation on Windows, please watch this link. You can download the Python from this link.

2. Python Array Example

I am using JetBrains PyCharm as my preferred IDE. You’re free to choose the IDE of your choice.

2.1 Creating an implementation file

Add the below code to the python script. The script contains several methods that will help understand the array module in deep. You’re free to play around with these methods as per your wish.

  • The access_elements() method will return the element from the array based on an index
  • The size() method retrieves the array length
  • The print_elements() method display the array elements
  • The add_element() method adds a new element into an existing array
  • The remove_element() method removes an element from the array
  • The slice_array() method returns a new array with the sub-elements while the original element remains unchanged
  • The search_element() method will find the index of the first occurrence of an element
  • The reverse_array() method will reverse the elements in an array
  • The count_element() method will count the occurrence of an element
  • The update_element() method will use the array index to modify the value with the help of the assignment operator

jcg-assignment-array.py

import array as arr

# creating array
int_arr = arr.array('i', [1, 2, 3, 4, 5])


def access_elements():
    print('first element = {}'.format(int_arr[0]))
    print('second element = {}'.format(int_arr[1]))
    print('last element = {}'.format(int_arr[-1]))


def size():
    print('array size = {}'.format(len(int_arr)))


def print_elements():
    print('array elements are: ')
    for ele in int_arr:
        print(ele, end=', ')


def add_element():
    # insert() adds element at the given index.
    # elements from the given index are shifted to right by one position.
    index = 0
    value = 7
    int_arr.insert(index, value)
    print('element = {} added at array index = {}'.format(value, index))
    # append() add an element at the end of array.
    value1 = 8
    int_arr.append(value1)
    print('element = {} added at the last'.format(value1))


def remove_element():
    try:
        value = 5
        # remove() removes the given element from the array
        # if not found ValueError is thrown
        int_arr.remove(value)
        print('element = {} removed from array'.format(value))
    except ValueError as e:
        print(e)


def slice_array():
    # slicing returns a new array with the sub_elements while the original array remains unchanged
    print(int_arr[3:])
    # the array slicing in python supports the negative numbers
    print(int_arr[:-2])


def search_element():
    try:
        key = 1
        # index() find the index of first occurrence of element
        # if not found ValueError is thrown
        index = int_arr.index(key)
        print("search key = {} found at index = {} in array".format(key, index))
    except ValueError as e:
        print(e)


def reverse_array():
    int_arr.reverse()
    print("reversed array = {}".format(int_arr))


def count_element():
    element = 4
    count = int_arr.count(element)
    print("count of {} is = {}".format(element, count))


def update_element():
    # use array index with the assignment operator to modify the value at the given index
    # if the index is invalid IndexError is thrown
    try:
        index = 3
        value = -9
        int_arr[index] = value
        print('value = {} updated at array index = {}'.format(value, index))
    except IndexError as e:
        print(e)


if __name__ == '__main__':
    access_elements()
    print()

    size()
    print()

    add_element()
    print_elements()
    print()
    print()

    remove_element()
    print_elements()
    print()
    print()

    slice_array()
    print()

    search_element()
    print()

    reverse_array()
    print()

    count_element()
    print()

    update_element()
    print_elements()

Run this python script and if everything goes well the output will be shown in the IDE console describing what an array module could do.

Console output

first element = 1
second element = 2
last element = 5

array size = 5

element = 7 added at array index = 0
element = 8 added at the last
array elements are: 
7, 1, 2, 3, 4, 5, 8, 

element = 5 removed from array
array elements are: 
7, 1, 2, 3, 4, 8, 

array('i', [3, 4, 8])
array('i', [7, 1, 2, 3])

search key = 1 found at index = 1 in array

reversed array = array('i', [8, 4, 3, 2, 1, 7])

count of 4 is = 1

value = -9 updated at array index = 3
array elements are: 
8, 4, 3, -9, 1, 7,

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

3. Summary

In this tutorial, we learned about the array module and different methods which we can use to play around with the module. You can download the source code of this tutorial from the Downloads section.

4. Download the Project

This was a tutorial on how to use array module in python.

Download
You can download the full source code of this example here: Python Array Example

Last updated on Feb. 24th, 2022

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button