Common Data Items and Methods of an Array in Python

Python | Command Data Items and Method of an Array: Here, we are going to learn about some of the common data items and methods of an array in Python. By IncludeHelp Last updated : January 14, 2024

Common Data Items and Methods of Python Array Class

List of common and most useful data items and methods of an array class in Python are:

Sr No Data Item/Method Description Example (Consider a is array name)
1 array.typecode Returns the typecode of the array a.typecode
2 array.itemssize Returns the item size of an element of the array a.itemsize
3 array.append(x) Appends x at the end of the array a.append(100)
4 array.count(x) Returns the occurrence of element x in the array a.count(10)
5 array.index(x) Returns the index of x in the array a.index(10)
6 array.insert(i,x) Inserts the element x at given index i in the array a.insert(2,10)
7 array.pop(i) Removes the item from the index i and returns the element a.pop(2)
8 array.remove(x) Removes the first occurrence of element x in the array a.remove(20)
9 array.reverse() Reverses the elements of the array a.reverse()
10 array.tolist() Converts array to a list with same items a.tolist()

Example

Python program demonstrating use of all above-written data items and methods.

# imporating array module to use array 
import array as arr


# declare and initialze array of type signed int
a = arr.array ("i", [10, 20, -30, 40, -50] )

# typecode
print ("Typecode of a: ", a.typecode)

# itemsize
print ("Item size of an element: ", a.itemsize);

# append new item at the end of the array 
a.append(60)
print ("Elements: ", a);

# array count(x)
print (a.count(20))

# index (X)
print ("Index: ", a.index(20))

# insert (i,x)
a.insert (2,99)
print ("Elements: ", a);

# pop (i)
print (a.pop(2), " is removed...")
print ("Elements: ", a);

# remove (x)
a.remove(-30)
print ("Elements: ", a);

# reverse
a.reverse ()
print ("Elements: ", a);

# tolist
print ("Elements (tolist): ", a.tolist ())
print ("Type of a: ", type (a))

Output

Typecode of a:  i
Item size of an element:  4
Elements:  array('i', [10, 20, -30, 40, -50, 60])
1
Index:  1
Elements:  array('i', [10, 20, 99, -30, 40, -50, 60])
99  is removed...
Elements:  array('i', [10, 20, -30, 40, -50, 60])
Elements:  array('i', [10, 20, 40, -50, 60])
Elements:  array('i', [60, -50, 40, 20, 10])
Elements (tolist):  [60, -50, 40, 20, 10]
Type of a:  <class 'array.array'>

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.