w3resource

Python: array module

array module - Efficient arrays of numeric values

This module defines an object type which can compactly represent an array of basic values: characters, integers, floating point numbers.

Arrays are sequence types and behave very much like lists, except that the type of objects stored in them is constrained. The following type codes are defined:

Type code C Type Python Type Minimum size in bytes
'b' signed char int 1
'B' unsigned char int 1
'u' PY-UNICODE Unicode character 2
'h' signed short int 2
'H' unsigned short int 2
'i' signed int int 2
'I' unsigned int int 2
'l' signed long int 4
'L' unsigned long int 4
'q' signed long long int 8
'Q' unsigned long long int 8
'f' float float 4
'd' double float 8

The module defines the following type:

class array.array(typecode[, initializer])

  • A new array whose items are restricted by typecode, and initialized from the optional initializer value, which must be a list, a bytes-like object, or iterable over elements of the appropriate type.
  • If given a list or string, the initializer is passed to the new array’s fromlist(), frombytes(), or fromunicode() method (see below) to add initial items to the array. Otherwise, the iterable initializer is passed to the extend() method.
  • A new array whose items are restricted by typecode, and initialized from the optional initializer value, which must be a list, a bytes-like object, or iterable over elements of the appropriate type.
  • If given a list or string, the initializer is passed to the new array’s fromlist(), frombytes(), or fromunicode() method (see below) to add initial items to the array. Otherwise, the iterable initializer is passed to the extend() method.

Example: Python array


Download the above Notebook from here.

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Finding the most common elements in an iterable:

Example:

# collections.Counter lets you find the most common
# elements in an iterable:

import collections
c = collections.Counter('helloworld')

print(c)

print (c.most_common(3))

Output:

Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, 'w': 1, 'r': 1, 'd': 1})
[('l', 3), ('o', 2), ('h', 1)]