Python Tutorial

Showing posts with label array. Show all posts
Showing posts with label array. Show all posts

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

Monday, February 18, 2013

Code snippet: Array initilize by odd number

a=[i for i in range(0,20) if i%2]
print a

Output:
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

Thursday, August 26, 2010

python multidimentional array

'''
   This code use python array syntax
'''
# declare a 2D array
array = [ [0 for col in range(3) ] for row in range(3)]

print array
# update array
array[1][1]=5
print array



Output:
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[0, 0, 0], [0, 5, 0], [0, 0, 0]]

Wednesday, August 18, 2010

python array example

'''
    This code use array syntax
'''
myArray=[]
myArray.append(1)
myArray.append(2)
myArray.append(6)
myArray.append(3)

print "Array length ",len(myArray)

'''
   access array data
'''
print myArray
for n in myArray:
    print n
for i in range(0,len(myArray)):
    print myArray[i]

'''
   sort array
'''
myArray.sort()
print myArray



Output:
Array length  4
[1, 2, 6, 3]
1
2
6
3
1
2
6
3
[1, 2, 3, 6]

Tuesday, August 17, 2010

python String Array

'''
    This code use string array syntax
'''
words=[]
words.append("Life")
words.append("is")
words.append("very")
words.append("easy")
words.append("with")
words.append("Python")

for word in words:
    print word

wordLed=len(words)
for i in range(0,wordLed):
    print words[i]

print words



Output:
Life
is
very
easy
with
Python
Life
is
very
easy
with
Python
['Life', 'is', 'very', 'easy', 'with', 'Python']