🐍
My Docs
PYTHONNOTES
PYTHONNOTES
  • Home
  • Downloads & Misc-Assets
  • README
  • Navigation
  • Curriculum
    • Outline
      • General Content
      • Python-Data-Structures-Unit
    • wk17
      • Outline-w17
      • homework
      • D1-Module 01 - Python I
        • Configuring Ubuntu for Python Web Development
        • Install Python
      • D2- Module 02 - Python II
      • D3- Module 03 - Python III
      • D4-Module 04 - Python IV
    • wk18
      • Outline-W-18
      • D1- Module 01 - Number Bases and Character Encoding
      • D2- Module 02 - Hash Tables I
        • Hash Table / Hash Map In Python:
        • Hash Table Use Cases
        • Practice
      • D3-Module 03 - Hash Tables II
      • D4- Module 04 - Searching and Recursion
    • wk19
      • Outline-W-19
      • D1- Module 01 - Linked Lists
        • Homework
          • Helpful Resource
      • D2- Module 02 - Queues and Stacks
      • D3- Module 03 - Binary Search Trees
        • BST Definition:
      • D4- Module 04 - Tree Traversal
        • Tree Traversals (Inorder, Preorder and Postorder)
    • wk20
      • Outline-W-20
      • D1-Graphs I
      • D2-Graphs 2
      • DFS
      • D4
  • Utilities
    • Utilites
      • Python Libraries
      • YouTube
      • Code Lab Notebook Embeds From Lecture
    • Code lab Notebooks
    • Repl.IT
      • Trinket
  • Abstract Data Structures
    • Algorithms
      • Algo-Resources
        • List-Of-Solutions-To-Common-Interview-Questions
      • Dijkstra's algorithm
      • Calculate a Factorial With Python - Iterative and Recursive
      • DFS
      • BFS
        • BFS Examples
      • Palendrome
    • Data Structures Overview
      • General Data Structures Notes
        • DS-Explained-Simple
      • Untitled
      • Algorithms
      • Dictionary
    • Abstract Data Structures:
      • Array
        • Extra-Array
        • Array Practice
      • Binary Search
      • Binary Tree
        • Binary Tree Explained
        • Find the maximum path sum between two leaves of a binary tree
      • Binary Search Tree
        • BST Explained
        • BST Insert
        • BST-Largest-Sub-Tree
      • Exotic
        • Tire
        • Dynamic Programming
      • Graphs
        • Overflow Practice Problems
        • Graphs Explained
        • Earliest Ancestor
        • _Mini Graph-Projects
          • # Social Graph
          • number of 1 islands
          • Searching and Generating Graphs
        • Graph FAQ
          • Graph DFS
        • Connected Components
        • Randomness
        • Graph BFS
        • Topological Sort
      • Hash Table
        • Hashmap or Hash tables
        • Hash Table and HashMap in Python
      • Heap
        • Heap Examples
      • String
      • Map
        • Examples
      • Queue
        • Queue Continued...
        • Queue Sandbox
        • Dequeue
      • Tree
        • In Order Traversal
        • Tree Equal ?
        • Ternary-search-trees
        • Red_Black Tree
        • Tree Mirror:
        • Tree Traversal
      • Recursion
        • Recursion Explained
          • Recursion Examples
      • Linked List
        • Linked List Background
        • Double Linked List
        • List Example
        • Examples (LL) continued
        • List Operations
      • Set
        • Set
        • Set Intersection Union
        • Disjoint Set
      • Sorting
        • In JavaScript
        • Merge Sort
        • Iterative Sorting
        • Recursive Sorting
        • Graph Topological Sort
        • SelectionSort
        • Quick Sort
        • Merge Sort
        • Insertion Sort
      • Stack
        • Stack Continued
        • Stack Part 3
      • Searching
        • Binary Search
        • Searching & Sorting Computational Complexity (JS)
  • practice
    • GCA Sprint Prep:
      • Practice Problems
      • Code Signal CGA Sprint Resources
      • CGA-Sprint Prep
    • Supplemental Practice:
      • Practice
      • JavaScript Algorithms
      • Industry Standard Algorithms
        • Interview Practice Resources
        • Write a Program to Find the Maximum Depth or Height of a Tree
      • Random Examples
      • Prompts
      • JS_BASICS
  • Resources
    • Python Cheat Sheet
      • Cheatsheet-v2
      • List Of Python Cheat Sheets
    • Youtube
    • PDF Downloads
    • Intro 2 Python
    • Dictionaries
      • Dictionaries Continued
    • Python VS JavaScript
    • Misc. Resources
    • Things To Internalize:
      • Functions
    • Intro To Python w Jupyter Notebooks
    • Calculating Big O
    • Useful Links
      • Awesome Python
      • My-Links
      • Beginners Guide To Python
  • Docs
    • Docs
      • Strings
        • Strings Continued
      • Touple
      • Values Expressions & Statments
      • Dictionaries, sets, files, and modules
        • Modules
      • Built-in Types
      • Built In Functions
        • Zip Function
      • Functions
      • Classes and objects
        • Inheritance
        • Classes
          • Python Objects & Classes
          • index
      • Dictionaries
      • Conditionals and loops
      • Lists
        • Reverse A List
        • Python Data Structures
        • More On Lists
        • Examples
          • More-Examples
        • List Compehensions
      • Basic Syntax
      • String-Methods
    • Queue & Stacks
  • quick-reference
    • My Medium Articles
    • Free Python Books
    • WHY Python?
    • Debugging
    • Python Snippets
    • Python3 Regex
    • Python Module Index:
      • Requests Module
    • Creating Python Modules
    • Useful Info
    • Python Glossary
    • Python Snippets
  • MISC
    • Built-in Methods & Functions
    • Data Structures Types
    • Math
    • Unsorted Examples
    • Outline
    • About Python
      • Python VS JavaScript
      • Python Modules & Python Packages
      • Misc
      • Python's Default Argument Values and Lists
      • SCRAP
  • Interview Prep
    • Interview Resources
      • By Example
        • Algo-Prep
      • Permutation
      • How to Write an Effective Resume of Python Developer
      • Interview Checklist
      • 150 Practice Problems & Solutions
  • Installations Setup & Env
    • python-setup
    • Installing Python Modules
    • Set Up Virtual Enviornment
  • Aux-Exploration
    • Related Studies
      • Self-Organizing Maps: Theory and Implementation in Python with NumPy
      • List Directory Contents
      • Employee Manager
      • OS Module
      • server-side-scripting
      • Web Scraping
      • Reading and Writing to text files in Python
      • General Data Structures
      • Touple
      • How to round Python values to whole numbers?
      • Python Array Module
      • Data Structures In JavaScript
      • Dunder Methods
      • Python GitHub API
      • JS-Event Loop
      • JavaScript Event Loop
      • Manipulating Files & Folders
  • experiments
    • Untitled
Powered by GitBook
On this page
  1. Aux-Exploration
  2. Related Studies

Python Array Module

Python Arrays | Python Array Module

Array is yet another interesting topic of python, which covers and requires a good knowledge of basics before actually applying it. But the article is of course, one more magic spell from fairy basket, so why would it be partial to any coder?

This article takes you from basic to advanced knowledge of Python array modules. So, let’s get started.

What is Array Module in Python?

The array module defines an object type that can compactly represent an array of some basic values as characters, integers, floating-point numbers.

Arrays are sequence types and behave similarly as lists, except that the type of objects stored in them is constrained. The module defines the following type:

class array.array(typecode[, initializer]): A new array whose items are restricted by the 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.

Here’s a list of such type codes-

Type Code

C Type

Python Type

Minimum size (bytes)

b

signed char

int

1

B

unsigned char

int

1

u

Py_UNICODE

Unicode character;

deprecated since Python 3.3

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

How to Import Python Arrays?

syntax

>>> import array

Indexing an Array in Python

>>>array=[5,9,5,9]print(array[1])

Output9

Python Array Class – Data Items

The class array has the following data items-

1. Array.typecodes: A string with all type codes.

2. Array.typecode: The typecode character used in creating the array.

3. Array.itemsize: The length of array

>>>arr.itemsize

4. array.append(x): Append new item with value x to the end of the array.

>>>arr.append

5. array.append(x): Append new item with value x to the end of the array.

**6. array.pop([i]):**removes the element “i”which is parsed.

>>>arr.pop

7. array.remove(x): Removes the first occurrence of x from the array.

>>>arr.remove

8. array.reverse(): Reverses the order of the items in the array.

>>>arr.reverse

9. array.index(x): Returns the smallest i such that i is the index of the first occurrence of x in the array.

>>>arr.index

10. array.insert(i, x): Inserts a new item with value x in the array before position i.

>>>arr.insert

11. array.buffer_info()

This returns a tuple that holds the address in memory and the length of elements in the buffer that holds the contents of the array in the runtime.

>>> arr.buffer

12. array.byteswap()

This performs an operation of bytes wap on an array in the runtime.

>>> arr.byte

13. array.count(x)

finds out how many 3s there are in our Python array in the runtime.

>>> arr.count

14. array.extend(iterable)

This attaches the iterable to the end of the array in Python in the runtime.

>>> arr.extend

15. array.fromlist(list)

This appends item from a list to the Python arrays in the runtime.

>>> arr.fromlist

16. array.fromunicode(s)

This appends the Unicode string in the runtime

>>> arr.unicode

17. array.index(x)

This returns the index for the first occurrence of x in the runtime.

>>> arr.index

18. array.tobytes()

returns a representation in bytes of the values of the array in the runtime

>>> arr.tobytes()

19. array.tolist()

converts the array into a list in the runtime.

>>> arr.tolist()

20. array.tounicode()

converts an array to a Unicode string in the runtime.

>>> arr.tounicode

How does Array Work in Python?

The array is stored in contiguous memory locations, where the index is a sequence of numbers that represents the values stored at every particular index.

To access or refer to the value at a particular index in an array we make use of a set of square brackets [ ],(as in lists) also we can use the for-in loop to iterate through the array. The array has indices and values.

Array Module Example in pythonimport array as arra=arr.array('I', [10 , 20 ,50] )print("Element at 0th index: " , a[0])print("Element at 1st index: " , a[1])print("Element at 2nd index: " , a[2])

Output

Element at 0th index: 10Element at 1st index: 20

Element at 2nd index: 50

Python Array Representation

Arrays can be declared in various ways and in different languages. The important points that should be considered are as follows:

  • Index always starts with 0.

  • We can access each element using its index.

  • The length of the array defines the capacity to store the elements.

Python Array Operations

Some of the basic operations supported by an array are:

  • Traverse – It prints all elements one by one.

  • Insertion – It adds an element at a given index.

  • Deletion – It deletes elements at the given index.

  • Search – It searches the element using the given index or by the value.

  • Update – It updates elements at the given index.

Searching Element in Python Array Example: from array import *array_techvidvan = array(‘i’, [0,1,2,3,4,5])print (array_techvidvan.index(3))

**Output:**1

Example of Traversing Array in Python from array import *array_TechVidvan = [0,1,2,3,4,5]for x in array_TechVidvan: print (x)

Output:

01

2

3

4

5

Creating Python Arrays

for creating an array of numeric values, the coder needs to import the array module in runtime.

Example to Create Array in Pythonimport array as arrp = arr.array('q', [1,5])print(p)

**Output:**array(‘q’, [1,5])

Accessing Python Array Elements

**Example to access Python Array Elements:**import array as arrp = arr.array('j', [2, 80])print("First element of list:", p[0])print("Second element of list:", p[1])

**Output:**First element of list: 2 Second element of list: 80

Changing and Adding Elements in Python Array

Arrays are mutable therefore their elements can be changed in a similar way as lists in the code.

Codeimport array as arrnumb = arr.array('k', [1, 109])numb[0] = 0print(numb)

**Output:**array(‘k’, [0,109])

adding elements in array

extend(): it appends iterable to the end of the array in any code.

Codenumb.extend([5])print(numb)

**Output:**array(‘i’, [1,30,5])

Removing Python Array Elements

Codeimport array as arrnumb = arr.array('k', [1, 2,3 ])del numb[2]print(numb)

**Output:**error

Codedel numbprint(numb)

**Output:**Traceback (most recent call last): NameError: name ‘numb’ is not defined

Searching an element in an Array

Codeimport arrayarr = array.array('k', [1, 2])print ("The new created array is : ", end ="")for k in range (0, 2): print (arr[k], end =" ")

Output: 1

Updating Elements in an Array

Codeimport arrayprint ("Array before", end =" ")for k in range (0,2): print ([k], end =" ")

**Output:**Array before [0] [1]

Looping Array Elements in Python

Codelist=[1,0]for i in list: print(i)

Output:

10

Calculating Length of an Array in Python

Codel=[1,0]i = len(l)print(i)

**Output:**2

Slicing Arrays in Python

By using the slicing operator (:), it’s possible to access a range of elements present in the array in Python programming language. The following code snippet demonstrates using the slicing operator with an array :

Codenumber_list = [2, 4, 22, 25, 24, 52, 46,10]for i in range(1,5): print(i)for j in range(5,8): print(j)

Output:

12

3

4

5

6

7

Arrays are mutable. Hence, their elements can be changed similarly as lists.The append() method is used for adding one element to an array while extend() method allows adding multiple elements. These new elements are added at the end of the array.

Although knowing how to deal with arrays isn’t a compulsory part of learning Python, being able to do so is surely an added advantage.Typically, the array module is generally required for interfacing with C code.

Python Lists Vs Arrays

Codea = [1, 3.5, "TechVidvan"]import array as arr# Errora = arr.array('d', [1, 3.5, "TechVidvan"])

Output:

Traceback (most recent call last): File “<string>”, line 3, in <module>

TypeError: must be real number, not str

Summary

At the end of the article, we got an idea of how an array is similar to a list in many aspects, but surely there is a difference. The array is not very much recommended in Python as stated earlier but knowing it will add to your knowledge.

A good coder is someone who knows every aspect of code, and practice is a definite key. Try and check out array() yourself. Happy Pythonning!

PreviousHow to round Python values to whole numbers?NextData Structures In JavaScript

Last updated 3 years ago