CodeBlessU
learn code with examples

Python Array

Array Introduction, Array vs List

# Example, array
import array

# int array, typecode i, initial elements specified in tuple
marks = array.array('i', (85, 95, 99, 100, 75) ) 
print(marks) #prints array('i', [85, 95, 99, 100, 75])

# float array, typecode f, empty
percentile_rank = array.array('f') 
print(percentile_rank) #prints array('f')

type(marks)

Array is similar to list (sequential data type) with additional constraints. While creating array, it require to specify type (char/ int / float ?) to be stored.

Advantage: Compact and efficient representation compare to list.
Limitation: Type once fixed can not be changed.

Python array supports char, short, int, long, long long, float and double - each with signed, unsigned. Python does not have all such data types, but python array facilitates user to specify it ONLY FOR array storage. Thanks to underlaying C implementation.


Import array module

# import module
import array

Type

  • class 'array.array'

Array type codes

Array type code is specified as char.
Type code C data type Python data type
'b' signed char int
'h' signed short int
'i' signed int int
'l' signed long int
'q' signed long long int
'f' float float
'B' unsigned char int
'H' unsigned short int
'I' unsigned int int
'L' unsigned long int
'Q' unsigned long long int
'd' double float

Array class details

Types

  • class array.array( typecode [, initializer] )
  • array.typecodes

Data items

  • array.typecode
  • array.itemsize

Methods

  • array.append( x )
  • array.buffer_info()
  • array.byteswap()
  • array.count( x )
  • array.extend( iterable )
  • array.frombytes( s )
  • array.fromfile( f, n )
  • array.fromlist( list )
  • array.fromunicode( s )
  • array.index( x )
  • array.insert( i, x )
  • array.pop( [i] )
  • array.remove( x )
  • array.reverse()
  • array.tobytes()
  • array.tofile( f )
  • array.tolist()
  • array.tostring()
  • array.tounicode()

Working with Array

You can check in details about Creating Array. Generally, what is Default Value for Array variable, Memory requirement for Array, How to find length of Array.

Array Index and Array Slice are described in details. Array supports various operations like: Replace element, Append at end, Extend at end, Insert at start/front, in middle, at end, Remove element by Value, Remove element by Index, Remove All, Reverse elements, Find occurrences of element in Array or Find if element is present or not, Find index of element.

In this page...

Copyright © All rights reserved.