Page 1 of 1

Working with Arrays in Python

#1 atik97  Icon User is offline

  • ???
  • member icon

Reputation: 143
  • View blog
  • Posts: 715
  • Joined: 16-September 08

Posted 26 January 2009 - 11:11 AM

Array

Simply an array is a group of related data items that share a common name. Arrays are of sequence types and behave very much like lists. The major difference is the elements of a list can be of different types while only the elements of same time construct an array. These element may be integers, floating point numbers or characters.

Arrays are so useful in mathematical operations. They can speeds up mathematical manipulations by several orders of magnitude.

In python, arrays are not a core data type like integers, floats or strings. There is a built-in standard module named ‘array’. In order to have access to the array type, the module ‘array’ must be imported. So, when we need to use array, we must import it-

from array import *



Array constructor

We have already known that arrays can hold data of same type. The type is specified by using a type code at the time when an array object is created. The constructor of an array is as follows-

identifierName=array(typecode[,initializer])



The type codes are as follows-

Type code Type Size in bytes
'b' signed integer 1
'B' unsigned integer 1
'u' Unicode character 2
'h' signed integer 2
'H' unsigned integer 2
'i' signed integer 2
'I' unsigned integer 2
'w' unicode character 4
'l' signed integer 4
'L' unsigned integer 4
'f' floating point 4
'd' floating point 8

Take a look how to create an array-

>>> from array import *
>>> a=array('i',[1,2,3,4,5])
>>> for i in a:
	print(i)

	
1
2
3
4
5 



An individual element of array can be called by index number-

>>> from array import *
>>> a=array('i',[2,3,4,5,9])
>>>a[0]
2
>>>a[1]
3
>>>a[1]+a[2]
7



Remember, first position of elements of array is 0, not 1.

Methods of array object

There are several methods to array object. Here is the most commonly used methods-
append()
extend()
index()
insert()
pop()
remove()
reverse()
fromlist()
fromfile()
tolist()
tofile()
tostring()

Add new item to array

You can use append(), extend(), insert() or fromlist() method to add new items to an existing array. Here is how to do it-

Example:Adding new items to array
>>> from array import *
>>> a=array('i',[2,3,4,5])
>>> print(a)
array('i', [2, 3, 4, 5])
>>> a.insert(0,1)
>>> print(a)
array('i', [1, 2, 3, 4, 5])
>>> a.append(6)
>>> print(a)
array('i', [1, 2, 3, 4, 5, 6])
>>> b=array('i',[7,8,9])
>>> a.extend(b)
>>> print(a)
array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> c=[2,4,6]
>>> a.fromlist(c)
>>> print(a)
array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 4, 6])



If you look at the example given above, you will see we have added new items to array using several methods. First method used here is insert() method. This method is used to insert a new element into a specified position. Thus it takes two arguments: position and then element. Next method used is append(), which takes only one argument. By using this method an element is added at the end of an array. If you wish to add several items from another array, then you can use extend method. It is also possible to add items from a list. fromlist() method adds all the items of that list into array.

Remove items from array

If you wish to remove an item from existing array, then you can use either the method remove() or pop(). Thie method remove() takes only one argument, the item to be removed. On the other hand, pop() also takes one argument, but it is optional. Then the argument is not supplied, it will remove the last element.

Example:Removing an entry from array
>>> from array import *
>>> a=array('i',[4,6,2,9])
>>> a.remove(2)
>>> print(a)
array('i', [4, 6, 9])
>>>a.pop()
>>>print(a)
array(‘i’,[4,6])



Some other methods of array object

Some other commonly used methods include index(), reverse(), tostring() and so on. The method index() is used to return the index of an element. Another method used is reverse(), which reverses the elements of an array. The method tostring() returns the array converted to string.

>>> from array import *
>>> a=array('i',[4,8,2,9,5])
>>> a.index(9)
3
>>> a.reverse()
>>> print(a)
array('i', [5, 9, 2, 8, 4])



Using Numeric Module

You can also get access of array by using Numeric module. You may probably feel more comfort using Numeric module rather than previous one. If you read this section, then you will find the reason behind this.

Example:Arrays using Numeric module
>>> from Numeric import *
>>> a = array([1, 2, 3.5, -9])
>>> print(a)
[ 1. 2. 3.5 -9. ]



Here you don’t need to specify type code at all! Here the result is shown with decimal points because one of the elements of the array contain decimal point(3.5). As a result python automatically converts all the elements to floating point numbers at the time of storing this valuses. The reason behind this is already known to us, array can only hold data of same type.

Note:The elements of an array should be either integer or floating point number.

Creating an empty array

You can also create an empty array by using the function zeros(). This function takes two parameters; number of elements and the type. Type is specified by either ‘Int’ in case of integer or ‘Float’ in case of floats.

Example: Creating empty array
>>> x = zeros(5, Int)
>>> print (x)
[0 0 0 0 0]
>>> y = zeros(4, Float)
>>> print (y)
[ 0. 0. 0. 0.]



zeros() function can be handy in mathematical manipulations. Let’s consider an example. Suppose you have to record the temperature of an object at an interval of one minute from the first minute. You can do that as follows-

Example:Use of zeros() function
from Numeric import *
counts = zeros(5, Int) 	#creating an empty array
for i in range(0, 10):
print ("Minute number", i)
t = input("Enter temperature")
counts[i] = t
print (“Data recorded successfully.”)



Hope it will help you.

Is This A Good Question/Topic? 1
  • +

Replies To: Working with Arrays in Python

#2 soldner  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 30
  • Joined: 07-December 09

Posted 01 February 2011 - 06:37 AM

Good explanation! Thanks!
Was This Post Helpful? 0
  • +
  • -

#3 Nallo  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 163
  • View blog
  • Posts: 255
  • Joined: 19-July 09

Posted 01 February 2011 - 03:58 PM

I am missing something here. Why and when would you use arrays instead of lists?
Was This Post Helpful? 0
  • +
  • -

#4 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4299
  • View blog
  • Posts: 12,060
  • Joined: 18-April 07

Posted 01 February 2011 - 04:18 PM

Nallo, I have provided a link below to part of the Python documentation that explains arrays. Essentially, an array is a way to force each element to be a specify basic type (like all integers) where lists allow you to put in an integer then a string then an object etc. It forces a structure which is homogeneous. Because of specifying a basic type and which is the same throughout, it can store values more compactly in memory.

Most people I know really don't need such a structure unless you are limited on memory and want to do some fast numerical calculations on a set of data which you know is of the same type.

8.6 - Efficient array of numeric values - Python.org Docs

Hope this helps! :)

This post has been edited by Martyr2: 01 February 2011 - 04:19 PM

Was This Post Helpful? 4
  • +
  • -

Page 1 of 1