0% found this document useful (0 votes)
15 views24 pages

History and Features of Python Programming

The document provides an overview of the Python programming language, detailing its history, features, and applications. It highlights Python's simplicity, versatility, and open-source nature, along with its various data types and constants. Additionally, it covers key concepts such as variables, identifiers, keywords, and the ability to assign values to variables.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views24 pages

History and Features of Python Programming

The document provides an overview of the Python programming language, detailing its history, features, and applications. It highlights Python's simplicity, versatility, and open-source nature, along with its various data types and constants. Additionally, it covers key concepts such as variables, identifiers, keywords, and the ability to assign values to variables.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Programming Language

Unit - I

History of Python

 Python was first developed by Guido van Rossum in the late 80‟s and early 90‟s
at the National Research Institute for Mathematics and Computer Science in the
Netherlands.
 It has been derived from many languages such as ABC, Modula-3, C, C++,
Algol- 68, SmallTalk, UNIX shell and other scripting languages.
 Since early 90‟s Python has been improved tremendously. Its version 1.0 was
released in 1991, which introduced several new functional programming tools.
 While version 2.0included list comprehension was released in 2000 by the Be
Open Python Labs team.
 Python 2.7 which is still used today will be supported till 2020.
 Currently Python 3.6.4 is already available. The newer versions have better features
like flexible string representation etc,
 Although Python is copyrighted, its source code is available under GNU General
Public License (GPL) like that Perl.
 Python is currently maintained by a core development team at the institute which
is directed by Guido Van Rossum.
 These days, from data to web development, Python has emerged as very powerful
and popular language. It would be surprising to know that python is actually older
than Java, R and JavaScript.
Features of Python

• Simple: Reading a program written in Python feels almost like reading english.
The main strength of Python which allows programmer to concentrate on the
solution to the problem rather than language itself.
• Easy to Learn: Python program is clearly defined and easily readable. The
structure of the program is simple. It uses few keywords and clearly defined
syntax.
• Versatile: Python supports development of wide range of applications such as
simple text processing, WWW browsers and games etc.
• Free and Open Source: It is an Open Source Software. So, anyone can freely
distribute it, read the source code, edit it, and even use the code to write new (free)
programs.
SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

1|Page
• High-level Language: While writing programs in Python we do not worry about
the low-level details like managing memory used by the program.
• Interactive: Programs in Python work in interactive mode which allows
interactive testing and debugging of pieces of code. Programmer can easily interact
with the interpreter directly at the python prompt to write their programs.
• Portable: It is a portable language and hence the programs behave the same on wide
variety of hardware platforms with different operating systems.
• Object Oriented: Python supports object-oriented as well as procedure-oriented
style of programming .While object-oriented technique encapsulates data and
functionality with in objects, Procedure oriented at other hand, builds programs
around procedure or functions.
• Interpreted: Python is processed at runtime by interpreter. So, there is no need
to compile a program before executing it. You can simply run the program. Basically
python converts source program into intermediate form called byte code.
• Dynamic and strongly typed language: Python is strongly typed as the interpreter
keeps track of all variables types. It's also very dynamic as it rarely uses what it
knows to limit variable usage.
• Extensible: Since Python is an open source software, anyone can add low-level
modules to the python interpreter. These modules enable programmers to add to
or customize their tools to work more efficiently.
• Embeddable: Programmers can embed Python within their C, C++, COM,
ActiveX, CORBA and Java Programs to give „scripting „capability for users.
• Extensive Libraries: Python has huge set of libraries that is easily portable across
different platforms with different operating systems.
• Easy maintenance: Code Written in Python is easy to maintain.
• Secure: This Programming language is secure for tampering. Modules can be
distributed to prevent altering of source code. Additionally, Security checks can
be easily added to implement additional security features.
• Robust: Python Programmers cannot manipulate memory directly, errors are
raised as exceptions that can be catch and handled by the program code. For
every syntactical mistake, a simple and easy to interpret message is displayed. All
these make python robust.
• Multi-threaded: Python supports executing more than one process of a program
simultaneously with the help of Multi-Threading.

SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

2|Page
• Garbage Collection: The Python run-time environment handles garbage
collection of all python objects. For this, a reference counter is maintained to
assure that no object that is currently in use is deleted.
Applications of Python
 Embedded scripting language: Python is used as an embedded scripting
language for various testing/ building/ deployment/ monitoring frameworks,
scientific apps, and quick scripts.
 3D Software: 3D software like Maya uses Python for automating small user tasks,
or for doing more complex integration such as talking to databases and asset
management systems.
 Web development: Python is an easily extensible language that provides good
integration with database and other web standards.
 GUI-based desktop applications: Simple syntax, modular architecture, rich text
processing tools and the ability to work on multiple operating systems makes Python
a preferred choice for developing desktop-based applications.
 Image processing and graphic design applications: Python is used to make 2D
imaging software such as Ink scape, GIMP, Paint Shop Pro and Scribus. It is also
used to make 3D animation packages, like Blender, 3ds Max, Cinema 4D,
Houdini, Light wave and Maya.
 Scientific and Computational applications: Features like high speed,
productivity and availability of tools, such as Scientific Python and Numeric
Python, have made Python a preferred language to perform computation and
processing of scientific data. 3D modeling software, such as Free CAD, and finite element
method software, like Abaqus, are coded in Python.
 Games: Python has various modules, libraries, and platforms that support
development of games. Games like Civilization-IV, Disney's Toon town Online,
Vega Strike, etc. are coded using Python.
 Enterprise and Business applications: Simple and reliable syntax, modules and
libraries, extensibility, scalability together make Python a suitable coding
language for customizing larger applications. For example, Reddit which was
originally written in Common Lips, was rewritten in Python in 2005. A large
part of Youtube code is also written in Python.
 Operating Systems: Python forms an integral part of Linux distributions.

SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

3|Page
Literal Constants
 In programming constants are referred to variables that cannot be changed.
 Generally Literal constants are classified in to three types.

Literal Constants

Numeric Literals Boolean Literals String Literals

Numeric Literals
 The value of a literal constant can be used directly in programs. For example,
7, 3.9, 'A', and "Hello" are literal constants.
 Numbers refers to a numeric value. You can use four types of numbers in
Python program- integers, long integers, floating point and complex
numbers.
 Numbers like 5 or other whole numbers are referred to as integers. Bigger whole
numbers are called long integers. For example, 535633629843L is a long integer.
 Numbers like are 3.23 and 91.5E-2 are termed as floating point numbers.
 Numbers of a + bj form (like -3 + 7j) are complex numbers.

Boolean Literals
 A Literals Boolean type can have one of the two values- True or False.

SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

4|Page
String Literals
 A string is a group of characters.
 Using Single Quotes ('): For example, a string can be written as 'HELLO'.
 Using Double Quotes ("): Strings in double quotes are exactly same as those in
single quotes. Therefore, 'HELLO' is same as "HELLO".
 Using Triple Quotes (''' '''): You can specify multi-line strings using triple quotes.
You can use as many single quotes and double quotes as you want in a string within
triple quotes.

Unicode Strings
 Unicode is a standard way of writing international text. That is,if you want to
write some text in your native language like hindi,then you need to have a
Unicode-enable text editor.
 Python allows you to specify Unicode text by prefixing the string with a u or U.
 For Example: u”Sample Unicode string”
 Note :The „U‟ prefix specifies that the file contains text written in language other than
English
Escape Sequences
 Some characters (like ", \) cannot be directly included in a string. Such
characters must be escaped by placing a backslash before them.

Raw Strings

 If you want to specify a string that should not handle any escape sequences and
want to display exactly as specified then you need to specify that string as a raw
string. A raw string is specified by prefixing r or R to the string.

SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

5|Page
Variables

 Variable means its value can vary. You can store any piece of information in a
variable.
 Variables are nothing but just parts of your computer‟s memory where information
is stored. To identify a variable easily, each variable is given an appropriate name.
Identifiers
Identifiers are names given to identify something. This something can be a
variable, function, class, module or other object. For naming any identifier, there are
some basic rules like:

 The first character of an identifier must be an underscore ('_') or a letter (upper


or lowercase).
 The rest of the identifier name can be underscores ('_'), letters (upper or
lowercase), or digits (0-9).
 Identifier names are case-sensitive. For example, myvar and myVar are not
the same.
 Punctuation characters such as @, $, and % are not allowed within identifiers.
 Examples of valid identifier names are sum, my_var, num1, r, var_20,
First, etc.,

 Examples of invalid identifier names are 1num, my-var, %check, Basic Sal,
H#R&A, etc.,
Keyword in Python
 Keywords are the reserved words in Python. We cannot use a keyword as
variable name, function name or any other identifier.
 Here's a list of all keywords in Python Programming.
 There are 33 keywords in Python 3.3. This number can vary slightly in course
of time.

 All the keywords except True, False and None are in lowercase and they must
be written as it is. The list of all the keywords are given below.

SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

6|Page
Keywords in
Python Programming Language

False class finally is return

None continue for lambda try

True def from nonlocal while

and del global not with

as elif if or yield

assert else import pass raise

break except in

Data Types
• The variables can hold values of different type called Data Type.
• Data type is a set of values and the allowable operations on those values.
• Python has a great set of useful data types. Python's data types are built in the
core of the language. They are easy to use and straightforward.
• Example a person age is stored in a number, his name is made only with
characters, and his address is made with mixture of numbers and characters.
• Python ha various standard data types to define the operations pos sible on them
and storage method for each of them.
• Python supports the following five standard data types.

1. Numbers
2. Strings
3. Lists
4. Tuple
5. Dictionary
Note: Python is pure object oriented programming [Link] refers to everything as an object including
numbers and strings.

SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

7|Page
Assigning or Initializing Values to Variables

In Python, programmers need not explicitly declare variables to reserve memory space. The
declaration is done automatically when a value is assigned to the variable using the equal sign
(=). The operand on the left side of equal sign is the name of the variable and the operand on its
right side is the value to be stored in that variable.
Example:

In Python, you can reassign variables as many times as you want to change the value
stored in them. You may even store value of one data type in a statement and other data type in
subsequent statement. This is possible because Python variables do not have specific types, i.e.,
we can assign integer to the variable, later we assign string to the same variable.
Example: Program to reassign value to a variable
val = ‘Hello’
print(val)
val = 100
print(val)
val=10.32
print(val)
Output: Hello
100
10.32
SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

8|Page
Multiple Assignments
 Python allows programmers to assign single value to more than one variable
simultaneously.
 For example
>>>sum = flag = a = b = 0

 In the above statement, all four integer variables are assigned a value [Link]
can also assign different values to multiple variables simultaneously as shown
below
For example
>>>sum, a, b, mesg = 0, 3, 5, “Result”

Here, variable sum a and b are integers (numbers) and mesg is assigned
“Result”.
Note: Removing a variable means that the reference from the name to the value has been deleted.
However, deleted variables can be used again in the code if and only if you reassign them some
value.

Boolean Type
A variable of Boolean type can have one of the two values- True or False. Similar to other
variables, the Boolean variables are also created while we assign a value to them or when we use
a relational operator on them.

Tuples
A tuple is similar to the list as it also consists of a number of values separated by
commas and enclosed within parentheses. The main difference between lists and tuples is that
you can change the values in a list but not in a tuple. This means that while tuple is a read only
data type, the list is not.

Example:

SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

9|Page
Lists
 Lists are the most versatile data type of Python language.
 A list consist of items separated by commas and enclosed within square
brackets the values stored in a list are accessed using indexes.
 The index of the first element being 0 and n-1 as that of the last element, where
n is the total number of elements in the list. Like strings, you can also use
the slice, concatenation and repetition operations on lists.
Example: Program to demonstrate operations on lists
list = ['a', 'bc', 78, 1.23]
list1 = ['d', 78]
print(list)
print(list[0])
print(list[1:3])
print(list[2:])
print(list * 2) print(list + list1)
Output:
['a', 'bc', 78, 1.23]
a
['bc', 78]
[78, 1.23]
['a', 'bc', 78, 1.23, 'a', 'bc', 78, 1.23]
['a', 'bc', 78, 1.23, 'd', 78]

Dictionary
 Python‟s dictionaries stores data in key-value pairs.
 The key values are usually strings and value can be of any data type. The key value
pairs are enclosed with curly braces ({ }).

 Each key value pair separated from the other using a colon (:). To access
any value in the dictionary, you just need to specify its key in square braces
([]).Basically dictionaries are used for fast retrieval of data.

Example:

SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

10 | P a g e
Basic Input and Output
input() method is used to request and get information from the user.
Example: name = input (' what is your class name? :')
Characters within quotes are called [Link] particular use of a string, for requesting input
from the user, is called a prompt.
Output: What is your class name? : I BCA 3
The underline is used here to indicate the user’s input.
print() method is used to display information on the screen.
Example: print('Welcome to My First Program!')
Output: Welcome to My First Program!

Comments

 Comments are the non-executable statements in a program. They are just added
to describe the statements in the program code.
 Comments make the program easily readable and understandable by the
programmer as well as other users who are seeing the code. The interpreter
simply ignores the comments.
 In Python, a hash sign (#) that is not inside a string literal begins a comment.
All characters following the # and up to the end of the line are part of the
comment.
Example:

Note: You can add a multiline string (triple quotes) in your code, and place your comment inside it:

SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

11 | P a g e
Indentation
o Whitespace at the beginning of the line is called indentation. These
whitespaces or the indentation are very important in Python.
o In a Python program, the leading whitespace including spaces and tabs at
the beginning of the logical line determines the indentation level of that
logical line.

Operators

 Operators are special symbols in Python that carry out arithmetic or


logical computation. The value that the operator operates on is called the
operand.
Example: >>> 2+3
5

Here, + is the operator that performs addition. 2 and 3 are the operands and 5 is the
output of the operation.

Python supports the following operators


1. Arithmetic operators
2. Comparison (Relational) operators
3. Unary Operators
4. Bitwise operators
5. Shift Operators
6. Logical Operators
7. Membership and Identity Operators
8. Assignment operators
9. Special operators
Arithmetic Operators

 Arithmetic operators are used to perform mathematical


operations likeaddition, subtraction, multiplication etc.

SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

12 | P a g e
 This operator will work on two operands.

Example: If a=100 and b=200 then look at the table below, to see the result of
arithmetic operations.

Comparision (Relational) Operators

 A Relational or Comparison operator checks the relationship between two operands.


If the relation is true, it returns 1; if the relation is false, it returns value 0
For Example assuming a=100 and b=2000, we can use the comparison operators
on them as specified in the following table.

Unary Operator

 Unary operators act on single operands. Python supports unary minus


operator.
 Unary minus operator is strikingly different from the arithmetic operator that
SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

13 | P a g e
operates on two operands and subtracts the second operand from the first
operand.
 When an operand is preceded by a minus sign, the unary operator negates its
value.
 For example, if a number is positive, it becomes negative when preceded with
a unary minus operator. Similarly, if the number is negative, it becomes positive
after applying the unary minus operator. Consider the given example.
b = 10 a = -(b)
The result of this expression, is a = -10, because variable b has a positive value. After
applying unary minus operator (-) on the operand b, the value becomes -10, which indicates it
as a negative value.

Bitwise Operators

 As the name suggests, bitwise operators perform operations at the bit level.
 These operators include bitwise AND, bitwise OR, bitwise XOR, and shift
operators.
 Bitwise operators expect their operands to be of integers and treat them as
a sequence of bits.
The truth tables of these bitwise operators are given below.

Example: If a=60 and b=13 then look at the table below, to see the result of Bitwise
operations.

Operator Description Example

& Operator copies a bit to the result if it


exists in both operands (a & b) =12
(means 0000 1100)
Binary

AND

SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

14 | P a g e
| It copies a bit if it exists in either
operand. (a | b) = 61
(means 0011 1101)
Binary OR

^ It copies the bit if it is set in one


operand but not both. (a ^ b) = 49
(means 0011 0001)
Binary

XOR

~ (~a ) = -61
It is unary and has the effect of 'flipping'
(means 1100 0011
Binary Ones bits.
in 2's complement
Complement form due to a signed
binary number
<< The left operands value is moved left by
a << 2 = 240
the number of bits specified by the right
operand. (means 1111 0000)
Binary Left
Shift

>> The left operands value is moved right by


the number of bits specified by the right a >> 2 = 15
Binary Right operand. (means 0000 1111)
Shift

Shift Operators

 Python supports two bitwise shift operators. They are shift left (<<) and shift
right (>>).

 These operations are used to shift bits to the left or to the right. The syntax
for a shift operation can be given as follows.

SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

15 | P a g e
Logical Operators

 Logical operators are used to simultaneously evaluate two conditions or


expressions with relational operators.
 Logical AND (and) If expressions on both the sides (left and right side) of
the logical operator are true, then the whole expression is true.

For example, If we have an expression (a>b) and (b>c), then the whole expression is true
only if both expressions are true. That is, if b is greater than a and c.

 Logical OR (or) operator is used to simultaneously evaluate two conditions or


expressions with relational operators. If one or both the expressions of the
logical operator is true, then the whole expression is true.
For example, If we have an expression (a>b) or (b>c), then the whole expression
is true if either b is greater than a or b is greater than c.

 Logical NOT (not) operator takes a single expression and negates the value of
the expression. Logical NOT produces a zero if the expression evaluates to a
non-zero value and produces a 1 if the expression produces a zero. In other
words, it just reverses the value of the expression.

For example, a = 10; b = not a; Now, the value of b = 0.

Membership and Identity Operators

Membership Operator

Python supports two types of membership operators–in and not in. These operators, test
for membership in a sequence such as strings, lists, or tuples.

 in Operator: The operator returns true if a variable is found in the specified


sequence and false otherwise. For example, a in nums returns 1, if a is a
member of nums.

 not in Operator: The operator returns true if a variable is not found in the
specified sequence and false otherwise. For example, a not in nums returns
1, if a is not a member of nums.

Identity Operators

 is Operator: Returns true if operands or values on both sides of the operator

SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

16 | P a g e
point to the same object and false otherwise. For example, if a is b returns 1,
if id(a) is same as id(b).

 is not Operator: Returns true if operands or values on both sides of the operator
does not point to the same object and false otherwise. For example, if a is not
b returns 1, if id(a) is not same as id(b).

Assignment Operators

 Assignment operators are used in Python to assign values to variables.


 a = 5 is a simple assignment operator that assigns the value 5 on the right to
the variable a on the left.
 There are various compound operators in Python like a += 5 that adds to the variable
and later assigns the same. It is equivalent to a = a + 5.

Assignment operators in Python

Operator Example Equivatent to

= x=5 x=5

+= x += 5 x=x+5

-= x -= 5 x=x-5

*= x *= 5 x=x*5

/= x /= 5 x=x/5

%= x %= 5 x=x%5

//= x //= 5 x = x // 5

**= x **= 5 x = x ** 5

&= x &= 5 x=x&5

|= x |= 5 x=x|5

SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

17 | P a g e
^= x ^= 5 x=x^5

>>= x >>= 5 x = x >> 5

<<= x <<= 5 x = x << 5

Operator Precedence

The operator precedence in Python are listed in the following table. It is


in descending order, upper group has higher precedence than the lower ones.

Operator precedence rule in Python

Operators Meaning

() Parentheses

** Exponent

+x, -x, ~x Unary plus, Unary minus, Bitwise NOT

Multiplication, Division, Floor division,


*, /, //, %
Modulus

+, - Addition, Subtraction

<<, >> Bitwise shift operators

& Bitwise AND

^ Bitwise XOR

| Bitwise OR

==, !=, >, >=, <, <=, is,


Comparison, Identity, Membership operators
is not, in, not in

SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

18 | P a g e
not Logical NOT

and Logical AND

Or Logical OR

Expressions
 An expression is any legal combination of symbols (like variables, constants
and operators) that represents a value.
 In Python, an expression must have at least one operand (variable or constant) and
can have one or more operators. On evaluating an expression, we get a value.
 Operand is the value on which operator is applied.

Generally Expressions are divided into the following types

1. Constant Expressions: One that involves only


constants. Example: 8 + 9 – 2
2. Integral Expressions: One that produces an integer result after
evaluating the expression.
Example: a = 10
3. Floating Point Expressions: One that produces floating point
results. Example: a * b / 2.0
4. Relational Expressions: One that returns either true or false value.
Example: c = a>b
5. Logical Expressions: One that combines two or more relational
expressions and returns a value as True or False.
Example: a>b and y! = 0
6. Bitwise Expressions: One that manipulates data at bit
level. Example: x = y&z
7. Assignment Expressions: One that assigns a value to a
variable. Example: c = a + b or c = 10
Example Program:
a = 20
b = 10
c = 15
d=5
print ("a:%d b:%d c:%d d:%d" % (a,b,c,d ))
e = (a + b) * c / d
print ("Value of (a + b) * c / d is ", e)
e = ((a + b) * c) / d
print ("Value of ((a + b) * c) / d is ", e)
e = (a + b) * (c / d)
print ("Value of (a + b) * (c / d) is ", e)
SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

19 | P a g e
e = a + (b * c) / d
print ("Value of a + (b * c) / d is ", e)
Output:
a: 20 b:10 c:15 d:5
Value of (a + b) * c / d is 90.0
Value of ((a + b) * c) / d is 90.0
Value of (a + b) * (c / d) is 90.0
Value of a + (b * c) / d is 50.0
Type Conversion
 In Python, it is just not possible to complete certain operations that involves
different types of data.
 For example, it is not possible to perform "2" + 4 since one operand is an integer
and the other is of string type.
>>>”20” + “30” >>> int(“2”) + int(“3”)
Output Output
‘2030’ 5
Another situation in which type conversion is must when we want to accept a
non-string value (integer or float) as an input. we know that input function returns string, so we
must typecast the input to numbers to perform calculations on them.

Example 1:
x=input (“Enter the first number”)

y=input (“Enter the second number”)

print(x+y)

Output: Enter the first number 6


Enter the second number 7
67

Example 2:
x=int(input(“Enter the first number))

y=int(input(“Enter the second number))

print(x+y)

Output:
Enter the first number 6
Enter the second number 7
13

SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

20 | P a g e
Python provides various built-in functions to convert value from one data type to
another datatype. The following are the functions return new object representing the converted
value. Some of them are given in the following table.

Type Casting vs Type Conversion

 We have done explicit conversion of a value from one data type to another.
This is known as type casting.
 However, in most of the programming languages including Python, there is an
implicit conversion of data types either during compilation or during run-time.
This is also known type conversion.
 For example, in an expression that has integer and floating point numbers (like
21 + 2.1 gives 23.1), the compiler will automatically convert the integer into
floating point number so that fractional part is not lost.
Arrays

An array is a collection of items stored at contiguous memory locations. The idea is to store multiple
items of the same type together. This makes it easier to calculate the position of each element by simply adding
an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the
name of the array).

Creating Array in Python

To create an array in Python, import the array module and use its array() function. We can create an
array of three basic types namely integer, float and Unicode characters using this function.

The array() function accepts typecode and initializer as a parameter value and returns an object of array
class.

Syntax
# importing
import array as array_name

# creating array
obj = array_name.array(typecode[, initializer])
SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

21 | P a g e
 typecode − The typecode character used to speccify the type of elements in the array.
 initializer − It is an optional value from which array is initialized. It must be a list, a bytes-like object,
or iterable elements of the appropriate type.

Example:
import array as arr
# creating an array with integer type
a = [Link]('i', [1, 2, 3])
print (type(a), a)
# creating an array with char type
a = [Link]('u', 'BAT')
print (type(a), a)
# creating an array with float type
a = [Link]('d', [1.1, 2.2, 3.3])
print (type(a), a)

Output:
array('i', [1, 2, 3])
array('u', 'BAT')
array('d', [1.1, 2.2, 3.3])

Python array type is decided by a single character typecode argument. The type codes and the
intended data type of array is listed below

typecode Python data type Byte size


'b' signed integer 1
'B' unsigned integer 1
'u' Unicode character 2
'h' signed integer 2
'H' unsigned integer 2
'i' signed integer 2
'I' unsigned integer 2
'l' signed integer 4
'L' unsigned integer 4
'q' signed integer 8
'Q' unsigned integer 8
'f' floating point 4
'd' floating point 8

Basic Operations on Python Arrays

 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.

SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

22 | P a g e
Accessing Array Element

We can access each element of an array using the index of the element.

Example:
from array import *
array1 = array('i', [10,20,30,40,50])
print (array1[0])
print (array1[2])

Output:
10
30

Insertion Operation
In insertion operation, we 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.
Example:
from array import *
array1 = array('i', [10,20,30,40,50])
[Link](1,60)
for x in array1:
print(x)
Ouput:
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.
Example:
from array import *
array1 = array('i', [10,20,30,40,50])
[Link](40)
for x in array1:
print(x)
Output:
10
20
30
50

Search Operation

You can perform a search operation on an array to find an array element based on its value or its index.

Example:
SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

23 | P a g e
from array import *
array1 = array('i', [10,20,30,40,50])
print ([Link](40))
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.

Example:
from array import *
array1 = array('i', [10,20,30,40,50])
array1[2] = 80
for x in array1:
print(x)

Output:
10
20
80
40
50

Array Methods

Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the first item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

24 | P a g e

You might also like