Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 18

Arrays

"Arrays" in Python are not the arrays in conventional programming languages


like C and Java, but closer to lists. A list can be a collection of either
homogeneous or heterogeneous elements, and may contain ints, strings or
other lists.

Basic Introduction to Arrays


 An array is a data structure that stores values of same data type. In
Python, this is the main difference between arrays and lists.
 While python lists can contain values corresponding to different data
types, arrays in python can only contain values corresponding to same
data type.
 If you are new to Python, get started with the Python Introduction
article.
 To use arrays in python language, you need to import the standard array
module. This is because array is not a fundamental data type like strings,
integer etc.
Here is how you can import array module in python :
from array import *
Once you have imported the array module, you can declare an array. Here is
how you do it:
arrayIdentifierName = array(typecode, [Initializers])
In the declaration above, arrayIdentifierName is the name of array, typecode
lets python know the type of array
and Initializers are the values with which array is initialized.
Typecodes are the codes that are used to define the type of array values or the
type of array. The table in the
parameters section shows the possible values you can use when declaring an
array and it's type.
Here is a real world example of python array declaration :
my_array = array('i',[1,2,3,4])
In the example above, typecode used is i. This typecode represents signed
integer whose size is 2 bytes.
Array is created in Python by importing array module to the python program. Then
the array is declared as shown below.

from array import *

arrayName = array(typecode, [Initializers])

Typecode are the codes that are used to define the type of value the array will hold.
Some common typecodes used are:

Typecod Value
e

b Represents signed integer of size 1 byte

B Represents unsigned integer of size 1 byte

c Represents character of size 1 byte

i Represents signed integer of size 2 bytes

I Represents unsigned integer of size 2 bytes

f Represents floating point of size 4 bytes

d Represents floating point of size 8 bytes

The below code creates an array named array1.


from array import *

array1 = array('i', [10,20,30,40,50])

for x in array1:
print(x)

When we compile and execute the above program, it produces the following result −
Output

10
20
30
40
50

Accessing Array Element


We can access each element of an array using the index of the element. The below
code shows how

from array import *

array1 = array('i', [10,20,30,40,50])

print (array1[0])

print (array1[2])

When we compile and execute the above program, it produces the following result −
which shows the element is inserted at index position 1.
Output

10
30

Insertion Operation
Insert operation is to insert one or more data elements into an array. Based on the
requirement, a new element can be added at the beginning, end, or any given index
of array.
Here, we add a data element at the middle of the array using the python in-built
insert() method.

from array import *

array1 = array('i', [10,20,30,40,50])

array1.insert(1,60)

for x in array1:
print(x)

When we compile and execute the above program, it produces the following result
which shows the element is inserted at index position 1.
Output
106020304050

Deletion Operation
Deletion refers to removing an existing element from the array and re-organizing all
elements of an array.
Here, we remove a data element at the middle of the array using the python in-built
remove() method.

from array import *

array1 = array('i', [10,20,30,40,50])

array1.remove(40)

for x in array1:
print(x)

When we compile and execute the above program, it produces the following result
which shows the element is removed form the array.
Output
10203050
Search Operation
You can perform a search for an array element based on its value or its index.
Here, we search a data element using the python in-built index() method.

from array import *

array1 = array('i', [10,20,30,40,50])

print (array1.index(40))

When we compile and execute the above program, it produces the following result
which shows the index of the element. If the value is not present in the array then th
eprogram returns an error.
Output
3
Update Operation
Update operation refers to updating an existing element from the array at a given
index.
Here, we simply reassign a new value to the desired index we want to update.

from array import *


array1 = array('i', [10,20,30,40,50])

array1[2] = 80

for x in array1:
print(x)

When we compile and execute the above program, it produces the following result
which shows the new value at the index position 2.

Multidimensional arrays
Section 18.1: Lists in lists
A good way to visualize a 2d array is as a list of lists. Something like this:
lst=[[1,2,3],[4,5,6],[7,8,9]]

here the outer list lst has three things in it. each of those things is another
list: The first one is: [1,2,3], the second

one is: [4,5,6] and the third one is: [7,8,9].

You can access these lists the same way you would access another
other element of a list, like this:
print (lst[0])
#output: [1, 2, 3]
print (lst[1])
#output: [4, 5, 6]
print (lst[2])
#output: [7, 8, 9]

You can then access the different elements in each of those lists the same
way:
print (lst[0][0])
#output: 1
print (lst[0][1])
#output: 2

Here the first number inside the [] brackets means get the list in that
position. In the above example we used the
number 0 to mean get the list in the 0th position which is [1,2,3]. The
second set of [] brackets means get the
item in that position from the inner list. In this case we used both 0 and 1
the 0th position in the list we got is the
number 1 and in the 1st position it is 2

You can also set values inside these lists the same way:

lst[0]=[10,11,12]
Now the list is [[10,11,12],[4,5,6],[7,8,9]]. In this example we changed the
whole first list to be a completely

new list.

lst[1][2]=15

Now the list is [[10,11,12],[4,5,15],[7,8,9]]. In this example we changed a


single element inside of one of the
inner lists.

First we went into the list at position 1 and changed the element within it
at position 2, which was 6 now
it's 15.
Section 18.2: Lists in lists in lists in..
This behaviour can be extended. Here is a 3-dimensional array:
[[[111,112,113],[121,122,123],[131,132,133]],[[211,212,213],[221,222,223],
[231,232,233]],[[311,312,
313],[321,322,323],[331,332,333]]]

As is probably obvious, this gets a bit hard to read. Use backslashes to


break up the different dimensions:
[[[111,112,113],[121,122,123],[131,132,133]],\
[[211,212,213],[221,222,223],[231,232,233]],\
[[311,312,313],[321,322,323],[331,332,333]]]
By nesting the lists like this, you can extend to arbitrarily high dimensions.
Accessing is similar to 2D arrays:
print(myarray)
print(myarray[1])
print(myarray[2][1])
print(myarray[1][0][2])
etc.
And editing is also similar:
myarray[1]=new_n-1_d_list
myarray[2][1]=new_n-2_d_list
myarray[1][0][2]=new_n-3_d_list #or a single number if you're dealing with 3D
arrays
etc.

Accessing Values in a Two Dimensional Array


The data elements in two dimesnional arrays can be accessed using two indices.
One index referring to the main or parent array and another index referring to the
position of the data element in the inner array. If we mention only one index then the
entire inner array is printed for that index position. The example below illustrates
how it works.
from array import *

T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]]

print(T[0])

print(T[1][2])

When the above code is executed, it produces the following result −


[11, 12, 5, 2]
10
To print out the entire two dimensional array we can use python for loop as shown
below. We use end of line to print out the values in different rows.
from array import *

T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]]


for r in T:
for c in r:
print(c,end = " ")
print()

When the above code is executed, it produces the following result −


11 12 5 2
15 6 10
10 8 12 5
12 15 8 6
Inserting Values in Two Dimensional Array
We can insert new data elements at specific position by using the insert() method
and specifying the index.
In the below example a new data element is inserted at index position 2.

from array import *


T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]]

T.insert(2, [0,5,11,13,6])

for r in T:
for c in r:
print(c,end = " ")
print()

When the above code is executed, it produces the following result −


11 12 5 2
15 6 10
0 5 11 13 6
10 8 12 5
12 15 8 6
Updating Values in Two Dimensional Array
We can update the entire inner array or some specific data elements of the inner
array by reassigning the values using the array index.
from array import *

T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]]

T[2] = [11,9]
T[0][3] = 7
for r in T:
for c in r:
print(c,end = " ")
print()

When the above code is executed, it produces the following result −


11 12 5 7
15 6 10
11 9
12 15 8 6
Deleting the Values in Two Dimensional Array
We can delete the entire inner array or some specific data elements of the inner
array by reassigning the values using the del() method with index. But in case you
need to remove specific data elements in one of the inner arrays, then use the
update process described above.
from array import *
T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]]

del T[3]

for r in T:
for c in r:
print(c,end = " ")
print()

When the above code is executed, it produces the following result −


11 12 5 2
15 6 10
10 8 12 5
Data Structures
What is a Data Structure?
Organizing, managing and storing data is important as it enables easier access
and efficient modifications. Data Structures allows you to organize your data in such
a way that enables you to store collections of data, relate them and perform
operations on them accordingly.

Types of Data Structures in Python


Python has implicit support for Data Structures which enable you to store and
access data. These structures are called List, Dictionary, Tuple and Set.

Python allows its users to create their own Data Structures enabling them to
have full control over their functionality. The most prominent Data Structures are
Stack, Queue, Tree, Linked List and so on which are also available to you in other
programming languages. So now that you know what are the types available to you,
why don’t we move ahead to the Data Structures and implement them using Python.

Types of Data Structures in Python


Python has implicit support for Data Structures which enable you to store and
access data. These structures are called List, Dictionary, Tuple and Set.

Python allows its users to create their own Data Structures enabling them to
have full control over their functionality. The most prominent Data Structures are
Stack, Queue, Tree, Linked List and so on which are also available to you in other
programming languages. So now that you know what are the types available to you,
why don’t we move ahead to the Data Structures and implement them using Python.
Lists
 Lists are used to store data of different data types in a sequential manner.

 There are addresses assigned to every element of the list, which is called as
Index.

 The index value starts from 0 and goes on until the last element called
the positive index.

 There is also negative indexing which starts from -1 enabling you to access
elements from the last to first. Let us now understand lists better with the help
of an example program.

Creating a list

To create a list, you use the square brackets and add elements into it accordingly. If
you do not pass any elements inside the square brackets, you get an empty list as
the output.

Adding Elements

Adding the elements in the list can be achieved using the append(), extend() and
insert() functions.

 The append() function adds all the elements passed to it as a single element.
 The extend() function adds the elements one-by-one into the list.
 The insert() function adds the element passed to the index value and increase
the size of the list too.
Deleting Elements

 To delete elements, use the del keyword which is built-in into Python but this
does not return anything back to us.
 If you want the element back, you use the pop() function which takes the
index value.
 To remove an element by its value, you use the remove() function.

Accessing Elements

Accessing elements is the same as accessing Strings in Python. You pass the
index values and hence can obtain the values as needed.

Other Functions

You have several other functions that can be used when working with lists.

 The len() function returns to us the length of the list.


 The index() function finds the index value of value passed where it has
been encountered the first time.
 The count() function finds the count of the value passed to it.
 The sorted() and sort() functions do the same thing, that is to sort the
values of the list. The sorted() has a return type whereas the sort()
modifies the original list.

Dictionary
Dictionaries are used to store key-value pairs.

 To understand better, think of a phone directory where hundreds and


thousands of names and their corresponding numbers have been added.

 Now the constant values here are Name and the Phone Numbers which are
called as the keys.

 And the various names and phone numbers are the values that have been fed
to the keys.

 If you access the values of the keys, you will obtain all the names and phone
numbers. So that is what a key-value pair is. And in Python, this structure is
stored using Dictionaries. Let us understand this better with an example
program.

Creating a Dictionary

Dictionaries can be created using the flower braces or using the dict() function. You
need to add the key-value pairs whenever you work with dictionaries.

Changing and Adding key, value pairs

To change the values of the dictionary, you need to do that using the keys. So, you
firstly access the key and then change the value accordingly. To add values, you
simply just add another key-value pair as shown below.
Deleting key, value pairs

 To delete the values, you use the pop() function which returns the value that
has been deleted.
 To retrieve the key-value pair, you use the popitem() function which returns a
tuple of the key and value.
 To clear the entire dictionary, you use the clear() function.

Other Functions

You have different functions which return to us the keys or the values of the key-
value pair accordingly to the keys(), values(), items() functions accordingly.
Tuple
 Tuples are the same as lists are with the exception that the data once entered
into the tuple cannot be changed no matter what.
 The only exception is when the data inside the tuple is mutable, only then the
tuple data can be changed. The example program will help you understand
better.

Creating a Tuple

You create a tuple using parenthesis or using the tuple() function.

Accessing Elements

Accessing elements is the same as it is for accessing values in lists.


Appending Elements

To append the values, you use the ‘+’ operator which will take another tuple to be
appended to it.

Other Functions
These functions are the same as they are for lists.

Sets
 Sets are a collection of unordered elements that are unique.

 Meaning that even if the data is repeated more than one time, it would be
entered into the set only once. It resembles the sets that you have learnt in
arithmetic.

 The operations also are the same as is with the arithmetic sets. An example
program would help you understand better.

Creating a set

Sets are created using the flower braces but instead of adding key-value pairs,
you just pass values to it.

Adding elements

To add elements, you use the add() function and pass the value to it.
Operations in sets

The different operations on set such as union, intersection and so on are shown
below.

 The union() function combines the data present in both sets.


 The intersection() function finds the data present in both sets only.
 The difference() function deletes the data present in both and outputs data
present only in the set passed.
 The symmetric_difference() does the same as the difference() function but
outputs the data which is remaining in both sets.
 Output:
{1, 2, 3, 4, 5, 6} ———- {1, 2, 3, 4, 5, 6}
{3, 4} ———- {3, 4}
{1, 2} ———- {1, 2}
{1, 2, 5, 6} ———- {1, 2, 5, 6}
set()

 Now that you have understood the built-in Data Structures, let’s get started
with the user-defined Data Structures. User-defined Data Structures, the
name itself suggests that users define how the Data Structure would work and
define functions in it. This gives the user whole control over how the data
needs to be saved, manipulated and so forth.

You might also like