Python Tutorial

Tuesday, January 14, 2014

Python array declaration by type

Python provides array declaration of specific types(ex-int, float, char). It is much faster(~10x) than normal array. Lets go to the code.

import array

# integer array declaration
a_int = array.array('i')
a_int.append(5)  # Error a_int.append(5.5)
print a_int[0]
a_int = array.array('i', range(10))
print a_int[7]

# float array declaration
a_float = array.array('f')
a_float.append(10)
print a_float[0]

# character array declaration
a_char = array.array('c')
a_char.append('A')
print a_char[0]

a_char = array.array('c', "python")
print a_char[1]

Output:
5
7
10.0
A
y

0 comments:

Post a Comment