Python

Python Array Example

Let’s talk about arrays in Python 3.4. Arrays are a way of grouping basic values (characters, integers, floating point numbers), they are sequence types and behave almost like lists, except that all the items in an array must be of the same type. Also, arrays are mutable, ordered and indexed.

1. The Basics

You probably know lists in Python, and arrays are pretty much the same, but with the constrained type. Another difference is that the array type is not built-in in the language, but a native module instead, called array. Let’s see a little example:
 
 


 
basic.py

import array

arr = array.array('i')
arr.append(1)
arr.append(2)
arr.append(3)
print("item in index 1: {}".format(arr[1]))
arr.remove(2)
print("item in index 1: {}".format(arr[1]))
print("index of 3: {}".format(arr.index(3)))

As you see, we are importing the module array, creating one, appending three items and then printing some data. The output can be found below.

$ python3 basic.py
item in index 1: 2
item in index 1: 3
index of 3: 1

That argument we are passing to the constructor of array.array (which is actually an alias for ArrayType), is the type code, that argument defines the type our array will hold. Let’s see the data types it supports:

  • 'i': Python’s int
  • 'b': Python’s bytes, which are essentially int
  • 'f': Python’s float
  • 'u': Python’s unicode character (deprecated)

These are actually just the basic types, and we will actually just talk about 'i' and 'b' in this example. The full list of data type codes can be found in the Python documentation, and as a memory help through array.typecodes:

$ python3
Python 3.4.3 (default, Oct 14 2015, 20:28:29)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import array
>>> array.typecodes # <- This returns a string containing all supported type codes
'bBuhHiIlLqQfd' # <- This is the string...

2. Utilities

Now, there are other ways of creating an array. You can instantiate one from a byte array or a list:

instantiate.py

import array

my_int_array = array.array('i')
my_char_array = array.array('b')
a_list = [1, 2, 3, 4]
some_bytes = b"some bytes"

my_int_array.fromlist(a_list)
my_char_array.frombytes(some_bytes)

print(my_int_array)
print(my_char_array)

Here we are defining two arrays, both of integers but one will be actually to hold ascii characters. Then we define a list of integers and a byte array, and adding them to the corresponding array. The output will look like this:

$ python3 instantiate.py
array('i', [1, 2, 3, 4])
array('b', [115, 111, 109, 101, 32, 98, 121, 116, 101, 115])

Also, as there are ways of creating arrays from lists and byte arrays, there are ways of creating lists and byte arrays from arrays. Let’s see tolist and tobytes.

utilities.py

import array

my_int_array = array.array('i')
my_char_array = array.array('b')
a_list = [1, 2, 3, 4]
some_bytes = "some bytes".encode('utf8')

my_int_array.fromlist(a_list)
my_char_array.frombytes(some_bytes)

print(my_int_array.tolist())
print(my_char_array.tobytes().decode('utf8'))

So, I copied the last example, but changed the print statement to print a list and a string, see:

$ python3 utilities.py
[1, 2, 3, 4]
some bytes

Of course, many of the methods lists provide, like index, pop, remove and reverse are provided by array.array as well.

3. We can treat them just as lists

Let’s work a little bit with arrays to actually see how similar they are to lists. Let’s sort an array (let’s imagine that Python doesn’t provide a built-in function to sort), we’ll use both bubble sort and quick sort for this example:

sort.py

import array

def is_valid(target):
    return type(target) == array.array or target.typecode != 'i'

def swap(target, a, b):
    buffer = target[a]
    target[a] = target[b]
    target[b] = buffer

def bubble_sort(target):
    if is_valid(target):
        swapped = True
        while swapped:
            swapped = False
            for i in range(0, len(target) - 1):
                if target[i] > target[i + 1]:
                    swap(target, i, i + 1)
                    swapped = True

def quick_sort(target, first=0, last=None):
    if is_valid(target):
        if last is None:
            last = len(target) - 1
        if first < last:
            split_point = partition(target, first, last)
            quick_sort(target, first, split_point - 1)
            quick_sort(target, split_point + 1, last)

def partition(target, first, last):
    pivot_value = target[first]
    left_mark = first + 1
    right_mark = last
    done = False
    while not done:
        while left_mark <= right_mark and target[left_mark] = pivot_value and right_mark >= left_mark:
            right_mark -= 1
        if right_mark < left_mark:
            done = True
        else:
            swap(target, left_mark, right_mark)
    swap(target, first, right_mark)
    return right_mark

my_array = array.array('i', [9, 5, 4, 7, 6, 8, 1, 3, 2])
bubble_sort(my_array)
print(my_array)

my_array = array.array('i', [9, 5, 4, 7, 6, 8, 1, 3, 2])
quick_sort(my_array)
print(my_array)

If you are familiar with these algorithms and the way we work with lists in Python, you’ll find that there is absolutely nothing new here, except the instantiation of the arrays and the validation we made. The output of the script:

$ python3 sort.py
array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9])
array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9])

4. Download the Code Project

This was a basic example on Python’s array module.

Download
You can download the full source code of this example here: python-array

Sebastian Vinci

Sebastian is a full stack programmer, who has strong experience in Java and Scala enterprise web applications. He is currently studying Computers Science in UBA (University of Buenos Aires) and working a full time job at a .com company as a Semi-Senior developer, involving architectural design, implementation and monitoring. He also worked in automating processes (such as data base backups, building, deploying and monitoring applications).
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