Unit 1
Unit 1
Python Programming
Python is a simple, general purpose, high level, and object-oriented programming
language.
What is Python?
Python is a general-purpose, dynamic, high-level, and interpreted programming
language. It supports Object Oriented programming approach to develop applications. It
is simple and easy to learn and provides lots of high-level data structures.
➢ Python is Interactive: You can actually sit at a Python prompt and interact with
the interpreter directly to write your programs.
History of Python
➢ Python was developed by Guido van Rossum in the late eighties and early nineties at
the National Research Institute for Mathematics and Computer Science in the
Netherlands.
R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 1
PYTHON PROGRAMMING
➢ Python is derived from many other languages, including ABC, Modula-3, C, C++,
Algol-68, SmallTalk, Unix shell, and other scripting languages.
➢ At the time when he began implementing Python, Guido van Rossum was also reading
the published scripts from "Monty Python's Flying Circus" (a BBC comedy series from
the seventies, in the unlikely case you didn't know). It occurred to him that he needed a
name that was short, unique, and slightly mysterious, so he decided to call the language
Python.
➢ Python is now maintained by a core development team at the institute, although Guido
van Rossum still holds a vital role in directing its progress.
➢ Python 2.0 was released on 16 October 2000 and had many major new features,
including a cycle detecting garbage collector and support for Unicode. With this release
the development process was changed and became more transparent and community-
backed.
➢ Python 3.0 (which early in its development was commonly referred to as Python 3000
or py3k), a major, backwards-incompatible release, was released on 3 December 2008
after a long period of testing. Many of its major features have been back ported to the
backwards-compatible Python 2.6.x and 2.7.x version series.
Python Features
Python provides many useful features to the programmer. These features make it the
most popular and widely used language. We have listed below few-essential features of
Python.
o Easy to use and Learn: Python has a simple and easy-to-understand syntax,
unlike traditional languages like C, C++, Java, etc., making it easy for beginners to
learn.
o Expressive Language: It allows programmers to express complex concepts in just
a few lines of code or reduces Developer's Time.
o Interpreted Language: Python does not require compilation, allowing rapid
development and testing. It uses Interpreter instead of Compiler.
R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 2
PYTHON PROGRAMMING
o Increased Productivity: Python has a simple syntax and powerful libraries that
can help developers write code faster and more efficiently. This can increase
productivity and save time for developers and organizations.
o Big Data and Machine Learning: Python has become the go-to language for big
data and machine learning. Python has become popular among data scientists and
machine learning engineers with libraries like NumPy, Pandas, Scikit-learn,
TensorFlow, and more.
LITERAL
Literals in Python are defined as the raw data assigned to variables or constants
while programming.
String Literals
Numeric Literals
Boolean Literals
Literal Collections
Special Literals
String literals:
String literals can be formed by enclosing a text in the quotes. We can use both single as
well as double quotes to create a string.
Example:
"Amala" , '12345'
Types of Strings:
a) Single-line String- Strings that are terminated within a single-line are known as Single
line Strings.
Example:
text1='hello'
Example:
1. text1='hello\
2. world'
3. print(text1)
'helloworld'
Example:
1. str2='''''welcome
2. to
3. BHARATHI'''
4. print str2
Output:
welcome
to
BHARATHI
Numeric literals:
Numeric Literals are immutable. Numeric literals can belong to following four different
numerical types.
14.print(float_1, float_2)
15.print(a, a.imag, a.real)
Output:
A Boolean literal can have any of the two values: True or False.
1. x = (1 == True)
2. y = (2 == False)
3. z = (3 == True)
4. a = True + 10
5. b = False + 10
6.
7. print("x is", x)
8. print("y is", y)
9. print("z is", z)
10.print("a:", a)
11.print("b:", b)
Output:
x is True
y is False
z is False
a: 11
b: 10
None is used to specify to that field that is not created. It is also used for the end of lists
in Python.
1. val1=10
2. val2=None
3. print(val1)
4. print(val2)
Output:
10
None
V. Literal Collections.
Python provides the four types of literal collection such as List literals, Tuple literals,
Dict literals, and Set literals.
List:
o List contains items of different data types. Lists are mutable i.e., modifiable.
o The values stored in List are separated by comma(,) and enclosed within square
brackets([]). We can store different types of data in a List.
1. list=['John',678,20.4,'Peter']
2. list1=[456,'AMALA']
3. print(list)
4. print(list + list1)
Output:
Dictionary:
R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 8
PYTHON PROGRAMMING
Example
Output:
Tuple:
Example
1. tup = (10,20,"Dev",[2,3,4])
2. print(tup)
Output:
Set:
1. set = {'apple','grapes','guava','papaya'}
2. print(set)
Output:
Python Constants
In Python, constants are usually declared and assigned in a module (a new file containing
variables, functions, etc which is imported to the main file).
Let's see how we declare constants in separate file and use it in the main file,
Create a constant.py:
# declare constants
PI = 3.14
GRAVITY = 9.8
Create a main.py:
In the above example, we created the constant.py module file. Then, we assigned the
constant value to PI and GRAVITY.
After that, we create the main.py file and import the constant module. Finally, we
printed the constant value.
Comparison chart
Constant Literal
Exampl const PI = 3.14; var radius = 5; var var radius = 5; var circumference
e circumference = 2 * PI * radius; = 2 * 3.14 * radius;
VARIABLES
gender = 'M'
message = "Keep Smiling"
price = 987.9
Output:
Keep Smiling
User Number is 101
In the program 5-2, the variable message holds string type value and so its content is
assigned within double quotes " " (can also be within single quotes ' '), whereas the value
of variable userNo is not enclosed in quotes as it is a numeric value. Variable declaration
is implicit in Python, means variables are automatically declared and defined when they
are assigned a value the first time. Variables must always be assigned values before they
are used in expressions as otherwise it will lead to an error in the program. Wherever a
variable name occurs in an expression, the interpreter replaces it with the value of that
particular variable.
Program : Write a Python program to find the area of a rectangle given that its length is
10 units and breadth is 20 units.
200
1. name = "A"
2. Name = "B"
3. naMe = "C"
4. NAME = "D"
5. n_a_m_e = "E"
6. _name = "F"
7. name_ = "G"
8. _name_ = "H"
9. na56me = "I"
10.
11.print(name,Name,naMe,NAME,n_a_m_e, NAME, n_a_m_e, _name, name_,_name, na56
me)
Output:
ABCDEDEFGFI
There are two types of variables in Python - Local variable and Global variable.
Let's understand the following variables.
Local Variable
Local variables are the variables that declared inside the function and have scope
within the function. Let's understand the following example.
Example -
1. # Declaring a function
2. def add():
3. # Defining local variables. They has scope only within a function
4. a = 20
5. b = 30
6. c=a+b
7. print("The sum is:", c)
8.
9. # Calling a function
10.add()
Output:
Explanation:
In the above code, we declared a function named add() and assigned a few variables
within the function. These variables will be referred to as the local variables which have
scope only inside the function.
Global Variables
Global variables can be used throughout the program, and its scope is in the entire
program. We can use global variables inside or outside the function.
A variable declared outside the function is the global variable by default. Python
provides the global keyword to use global variable inside the function. If we don't use
the global keyword, the function treats it as a local variable. Let's understand the
following example.
R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 13
PYTHON PROGRAMMING
Example -
Output:
101
Welcome ToJavatpoint
Welcome ToJavatpoint
Explanation:
In the above code, we declare a global variable x and assign a value to it. Next, we
defined a function and accessed the declared variable using the global keyword inside the
function. Now we can modify its value. Then, we assigned a new string value to the
variable x.
Now, we called the function and proceeded to print x. It printed the as newly assigned
value of x.
Delete a variable
We can delete the variable using the del keyword. The syntax is given below.
Syntax -
1. del <variable_name>
In the following example, we create a variable x and assign value to it. We deleted
variable x, and print it, we get the error "variable x is not defined". The variable x will
no longer use in future.
Example -
1. # Assigning a value to x
2. x=6
3. print(x)
4. # deleting a variable.
5. del x
6. print(x)
Output:
print(x)
We can print multiple variables within the single print statement. Below are the example
of single and multiple printing values.
1. a=5
2. b=6
3. # printing multiple variables
4. print(a,b)
5. # separate the variables by the comma
6. Print(1, 2, 3, 4, 5, 6, 7, 8)
Output:
56
12345678
IDENTIFIERS
In programming languages, identifiers are names used to identify a variable,
function, or other entities in a program. The rules for naming an identifier in Python are
as follows:
• The name should begin with an uppercase or a lowercase alphabet or an underscore sign
(_). This may be followed by any combination of characters a–z, A–Z, 0–9 or underscore
(_). Thus, an identifier cannot start with a digit.
• It can be of any length. (However, it is preferred to keep it short and meaningful).
• It should not be a keyword or reserved word
• We cannot use special symbols like !, @, #, $, %, etc., in identifiers.
PYTHON KEYWORDS
Keywords are reserved words. Each keyword has a specific meaning to the Python
interpreter, and we can use a keyword in our program only for the purpose for which it
has been defined. As Python is case sensitive.
Python contains thirty-five keywords in the most recent version, i.e., Python 3.8.
Here we have shown a complete list of Python keywords for the reader's reference.
DATA TYPES
Every value belongs to a specific data type in Python. Data type identifies the type
of data values a variable can hold and the operations that can be performed on that data.
Figure 5.6 enlists the data types available in Python.
Number
Number data type stores numerical values only. It is further classified into three
different types: int, float and complex.
Boolean data type (bool) is a subtype of integer. It is a unique data type, consisting
of two constants, True and False. Boolean True value is non-zero, non-null and non-
empty. Boolean False is the value zero.
Let us now try to execute few statements in interactive mode to determine the data type
of the variable using built-in function type().
Example
>>> num1 = 10
>>> type(num1)
<class 'int'>
>>> num2 = -1210
>>> type(num2)
<class 'int'>
>>> var1 = True
>>> type(var1)
<class 'bool'>
>>> float1 = -1921.9
>>> type(float1)
<class 'float'>
>>> float2 = -9.8*10**2
>>> print(float2, type(float2))
-980.0000000000001 <class 'float'>
>>> var2 = -3+7.2j
>>> print(var2, type(var2))
(-3+7.2j) <class 'complex'>
Variables of simple data types like integers, float, boolean, etc., hold single values.
But such variables are not useful to hold a long list of information, for example, names of
R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 18
PYTHON PROGRAMMING
the months in a year, names of students in a class, names and numbers in a phone book or
the list of artefacts in a museum. For this, Python provides data types like tuples, lists,
dictionaries and sets.
Sequence
(A) String
String is a group of characters. These characters may be alphabets, digits or special
characters including spaces. String values are enclosed either in single quotation marks
(e.g., ‘Hello’) or in double quotation marks (e.g., “Hello”). The quotes are not a part of
the string, they are used to mark the beginning and end of the string for the interpreter.
For example,
>>> str1 = 'Hello Friend'
>>> str2 = "452"
We cannot perform numerical operations on strings, even when the string contains a
numeric
value, as in str2.
(B) List
List is a sequence of items separated by commas and the items are enclosed in
square
brackets [ ].
Example 5.4
#To create a list
>>> list1 = [5, 3.4, "New Delhi", "20C", 45]
#print the elements of the list list1
>>> print(list1)
[5, 3.4, 'New Delhi', '20C', 45]
(C) Tuple
Set
Set is an unordered collection of items separated by commas and the items are
enclosed in curly brackets { }. A set is similar to list, except that it cannot have duplicate
entries. Once created, elements of a set cannot be changed.
Example 5.6
#create a set
>>> set1 = {10,20,3.14,"New Delhi"}
>>> print(type(set1))
<class 'set'>
>>> print(set1)
{10, 20, 3.14, "New Delhi"}
#duplicate elements are not included in set
None
None is a special data type with a single value. It is used to signify the absence of
value in a situation. None supports no special operations, and it is neither same as False
nor 0 (zero).
Example 5.7
>>> myVar = None
>>> print(type(myVar))
<class 'NoneType'>
>>> print(myVar)
None
Mapping
R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 20
PYTHON PROGRAMMING
Mapping is an unordered data type in Python. Currently, there is only one standard
mapping data type in Python called dictionary.
(A) Dictionary
Dictionary in Python holds data items in key-value pairs. Items in a dictionary are
enclosed in curly brackets { }.
Dictionaries permit faster access to data. Every key is separated from its value using a
colon (:) sign. The key : value pairs of a dictionary can be accessed using the key. The
keys are usually strings and their values can be any data type. In order to access any value
in the
dictionary, we have to specify its key in square brackets [ ].
Example 5.8
#create a dictionary
>0>> dict1 = {'Fruit':'Apple',
'Climate':'Cold', 'Price(kg)':120}
>>> print(dict1)
{'Fruit': 'Apple', 'Climate': 'Cold',
'Price(kg)': 120}
>>> print(dict1['Price(kg)'])
120
Sometimes we may require to change or update the values of certain variables used
in a program. However, for certain data types, Python does not allow us to change the
values once a variable of that type has been created and assigned values. Variables whose
values can be changed after they are created and assigned are called mutable. Variables
whose values cannot be changed after they are created and assigned are called immutable.
When an attempt is made to update the value of an immutable variable, the old variable is
destroyed and a new variable is created by the same name in memory.
Python data types can be classified into mutable and immutable as shown in Figure 5.7.
Python input() function is used to get input from the user. It prompts for the user
input and reads a line. After reading data, it converts it into a string and returns that. It
throws an error EOFError if EOF is read.
Signature
1. input ([prompt])
Parameters
Return
Here, we are using this function get user input and display to the user as well.
Output:
Enter a value: 45
You entered: 45
The input() method returns string value. So, if we want to perform arithmetic operations,
we need to cast the value first. See the example below.
Output:
Enter an integer: 12
Input function
In Python, we have the input() function for taking the user input. The input()
function prompts the user to enter data.It accepts all user input as string. The user may
enter a number or a string but the input() function treats them as strings only. The syntax
for input() is:
input ([Prompt])
Prompt is the string we may like to display on the screen prior to taking the input,
and it is optional. When a prompt is specified, first it is displayed on the screen after
which the user can enter data. The input() takes exactly what is typed from the keyboard,
converts it into a string and assigns it to the variable on left-hand side of the assignment
operator (=). Entering data for the input function is terminated by pressing the enter key.
R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 23
PYTHON PROGRAMMING
Example
The variable fname will get the string ‘Arnab’, entered by the user. Similarly, the
variable age will get the string ‘19’. We can typecast or change the datatype of the string
data accepted from user to an appropriate numeric value. For example, the following
statement will convert
the accepted string to an integer. If the user enters any non-numeric value, an error will
be generated.
Example
#function int() to convert string to integer
>>> age = int( input("Enter your age:"))
Enter your age: 19
>>> type(age)
<class 'int'>
Python print() function prints the given object on the screen or other standard
output devices.
Signature
1. print(object(s), sep=separator, end=end, file=file, flush=flush)
Parameters
object(s): It is an object to be printed. The Symbol * indicates that there may be more
than one object.
sep='separator' (optional): The objects are separated by sep. The default value of sep is
' '.
file (optional): - The file must be an object with write(string) method. If it is omitted,
sys.stdout will be used which prints objects on the screen.
flush (optional): If True, the stream is forcibly flushed. The default value of flush is
False.
Return
Output:
x=7
x=7=y
The below example use print() with separator and end parameters.
1. x = 7
2. print("x =", x, sep='00000', end='\n\n\n')
3. print("x =", x, sep='0', end='')
Output:
a =000007
a =07
In Python, we may import functions from one module into our program, or as we
say into, another module.
For this, we make use of the import Python keyword. In the Python window, we
add the next to import keyword, the name of the module we need to import.
There are several standard modules for Python. The complete list of Python standard
modules is available.
Code
Output:
COMMENTS
Comments are used to add a remark or a note in the source code. Comments are
not executed by interpreter.
They are added with the purpose of making the source code easier for humans to
understand..
In Python, a comment starts with # (hash sign).Everything following the # till the
end of that line is treated as a comment and the interpreter simply ignores it while
executing the statement.
Example
Output:
30
Python single-line comment starts with a hashtag symbol with no white spaces
(#) and lasts till the end of the line. If the comment exceeds one line then put a hashtag
on the next line and continue the comment. Python’s single-line comments are proved
useful for supplying short explanations for variables, function declarations, and
expressions. See the following code snippet demonstrating single line comment:
Code 1:
Python3
# This is a comment
Output
BHARATHI WOMEN’S COLLEGE
Code 2:
Python3
"""
print("HELLO")
Output
HELLO
INDENTATION IN PYTHON
o It is not too much complicated and not more focused on the syntax.
o It is much faster and efficient than the other programming languages.
o Python code can be easily implemented and easily written, and easily be
executable.
Some basic Indentation Rules that are used in Python programming Language
o There is a proper indentation for a particular block of code that must be maintained
while beginning and ending any code block.
o A programmer can split the indentation into multiple lines by using a backslash.
o If any block where proper indentation is not maintained, the python compile will
throw the indentation error.
o Being consistent in following the indentation rule is quite confusing for a
programmer if the code is too large or contains lots of lines of code.
o But indentation helps us implement the code using simple syntax, rather than
applying brackets for every block of code, as we do in other programming
languages.
o Not only it is easy for us, but also it saves our time and reduces the lines of code;
hence ultimately, speed increases and execution tile reduces.
o The number of whitespace for a particular block of code is already fixed. If we use
nested conditional statements, then the number of whitespaces has increased,
according to the rule of sub-sub statements.
Example program
if 5 > 2:
output:
OPERATORS
ARITHMETIC OPERATORS
Python supports arithmetic operators that are used to perform the four basic
arithmetic operations as well as modular division, floor division and exponentiation.
Relational Operators
Relational operator compares the values of the operands on its either side and determines
the relationship among them. Assume the Python variables num1 = 10, num2 = 0, num3
= 10, str1 = "Good", str2 = "Afternoon" for the following examples:
Assignment Operators
Assignment operator assigns or changes the value of the variable on its left.
Logical Operators
There are three logical operators supported by Python. These operators (and, or,
not) are to be written in lower case only. The logical operator evaluates to either True or
False based on the logical operands on either side. Every value is logically either True or
False. By default, all values are True except None, False, 0 (zero), empty collections "",
(), [], {}, and few other special values. So if we say num1 = 10, num2 = -20, then both
num1 and num2 are logically True.
Table 5.6 Logical operators in Python
Identity Operators
Identity operators are used to determine whether the
value of a variable is of a certain type or not. Identity
operators can also be used to determine whether twovariables are referring to the same
object or not. There are two identity operators.
Membership Operators
TYPE CONVERSION
The program was expected to display double the value of the number received and
store in variable num1. So if a user enters 2 and expects the program to display 4 as the
output, the program displays the following result:
Explicit Conversion
Explicit conversion, also called type casting happens when data type conversion
takes place because the programmer forced it in the program. The general form of an
explicit data type conversion is:
(new_data_type) (expression)
With explicit type conversion, there is a risk of loss of information since we are
forcing an expression to be of a specific type. For example, converting a floating value of
x = 2 0.67 into an integer type, i.e., int(x) will discard the fractional part .67. Following
are some
of the functions in Python that are used for explicitly converting an expression or a
variable to a different type.
num1 = 10
num2 = 20
num3 = num1 + num2
print(num3)
print(type(num3))
num4 = float(num1 + num2)
print(num4)
print(type(num4))
Output:
30
<class 'int'>
30.0
<class 'float'>
#Program
#Explicit type conversion from float to int
num1 = 10.2
num2 = 20.6
num3 = (num1 + num2)
print(num3)
print(type(num3))
num4 = int(num1 + num2)
print(num4)
print(type(num4))
Output:
30.8
<class 'float'>
30
<class 'int'>
On execution, program gives an error as shown in Figure 5.11, informing that the
interpreter cannot convert an integer value to string implicitly. It may appear quite
intuitive that the program should convert the integer value to a string depending upon the
usage.
However, the interpreter may not decide on its own when to convert as there is a
risk of loss of information. Python provides the mechanism of the explicit type
conversion so that one can clearly state the desired outcome. Program 5 works perfectly
using explicit type casting:
Similarly, type casting is needed to convert float to string. In Python, one can
convert string to integer or float values whenever required.
#Program
#Explicit type conversion
icecream = '25'
brownie = '45'
#String concatenation
price = int(icecream)+int(brownie)
print("Total Price Rs." + str(price))
Output:
Total Price Rs.2545
Total Price Rs.70
Implicit Conversion
Implicit conversion, also known as coercion, happens when data type conversion is
done automatically by Python and is not instructed by the programmer.
Output:
30.0
<class 'float'>
EXPRESSION
Example:
a+b
c
s-1/7*f
Types of Expressions:
# Constant Expressions
x = 15 + 1.3
print(x)
Output
16.3
Integral expressions: Integral Expressions are those which produce integer results
after implementing all the automatic and explicit type conversions.
Examples:
x, x * y, x + int( 5.0)
where x and y are integer variables.
# Integral Expressions
a = 13
b = 12.0
c = a + int(b)
print(c)
Output
25
Floating expressions: Float Expressions are which produce floating point results
after implementing all the automatic and explicit type conversions.
Examples:
x + y, 10.75
where x and y are floating point variables.
Relational expressions: Relational Expressions yield results of type bool which
takes a value true or false. When arithmetic expressions are used on either side of a
relational operator, they will be evaluated first and then the results compared.
Relational expressions are also known as Boolean expressions.
Examples:
x <= y, x + y > 2
PYTHON - ARRAYS
Array is a container which can hold a fix number of items and these items should be of
the same type. Most of the data structures make use of arrays to implement their
algorithms. Following are the important terms to understand the concept of Array.
Element− Each item stored in an array is called an element.
Index − Each location of an element in an array has a numerical index, which is
used to identify the element.
Array Representation
Arrays can be declared in various ways in different languages. Below is an illustration.
As per the above illustration, following are the important points to be considered.
Index starts with 0.
Array length is 10 which means it can store 10 elements.
Each element can be accessed via its index. For example, we can fetch an element
at index 6 as 9.
PROCESSING ARRAYS:
An array in Python:
#output
#array('i', [10, 20, 30])
First we included the array module, in this case with import array as arr .
Then, we created a numbers array.
We used arr.array() because of import array as arr .
Inside the array() constructor, we first included i, for signed integer. Signed integer
means that the array can include positive and negative values. Unsigned integer,
with H for example, would mean that no negative values are allowed.
Lastly, we included the values to be stored in the array in square brackets.
Keep in mind that if you tried to include values that were not of i typecode, meaning they
were not integer values, you would get an error:
#output
#Traceback (most recent call last):
# File "/Users/dionysialemonaki/python_articles/demo.py", line 14, in <module>
# numbers = arr.array('i',[10.0,20,30])
#TypeError: 'float' object cannot be interpreted as an integer
In the example above, I tried to include a floating point number in the array. I got an error
because this is meant to be an integer array only.
R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 44
PYTHON PROGRAMMING
#output
#array('d', [10.0, 20.0, 30.0])
The example above imported the array module via from array import * and created an
array numbers of float data type. This means that it holds only floating point numbers,
which is specified with the 'd' typecode.
To find out the exact number of elements contained in an array, use the built-
in len() method.
It will return the integer number that is equal to the total number of elements in the array
you specify.
#output
#3
In the example above, the array contained three elements – 10, 20, 30 – so the length
of numbers is 3.
Each item in an array has a specific address. Individual items are accessed by referencing
their index number.
Indexing in Python, and in all programming languages and computing in general, starts
at 0. It is important to remember that counting starts at 0 and not at 1.
To access an element, you first write the name of the array followed by square brackets.
Inside the square brackets you include the item's index number.
array_name[index_value_of_item]
#output
#10
#20
#30
ARRAY METHODS:
Following are the basic operations supported by an array.
Traverse − print all the array elements one by one.
Insertion − Adds an element at the given index.
Deletion − Deletes an element at the given index.
Search − Searches an element using the given index or by the value.
Update − Updates an element at the given index.
Array is created in Python by importing array module to the python program. Then the
array is declared as shown eblow.
Typecode are the codes that are used to define the type of value the array will hold. Some
common typecodes used are:
Typecode Value
Before lookign at various array operations lets create and print an array using python.
The below code creates an array named array1.
from array import *
for x in array1:
print(x)
When we compile and execute the above program, it produces the following result −
Output
10
20
30
40
R.NISHA M.Sc., M.Phil.,B.Ed, BHARATHI WOMEN’S COLLEGE - KALLAKURICHI Page 47
PYTHON PROGRAMMING
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.
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
10
60
20
30
40
50
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.
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
10
20
30
50
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.
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.
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.
Output
10
20
80
40
50