Sunday 6 April 2014

Different methods used in array in PYTHON

#!/usr/local/bin/python2.7
# pleases follow the indention as it is most important in python. python don't use begin/end, if/end if or loop/
#end loop so python identify statement by indention.

from array import *
my_array = array('i', [1,2,3,4,5,6,7,8,9])

#inserting in nth position .insert(position,value)
my_array.insert(0,12)

#appending value to to the last position
my_array.append(10)

#extending python array using extend method

my_extnd_array = array('i', [7,8,9,10])
my_array.extend(my_extnd_array) # extend(array object)

#add item from list into array using fromlist
lst = [13,14,15]
my_array.fromlist(lst)

#check the number of occurance of an element in array
print('\n9 occured %d times'%my_array.count(9))

#convert any array element to list using tolist() method
c=my_array.tolist()

#remove element from the list from any position
my_array.remove(4) # remove element from 4th position

#reverse elements in a python array using reverse method
my_array.reverse()

#remove element from the last position using pop method
my_array.pop()

#Search any element by index using index method
print('\nElement in 6th position is %d'%my_array.index(6))

#print array list
for i in my_array:
  print(i)

No comments: