IPP Unit-1 Material
IPP Unit-1 Material
Python Overview
Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to
be highly readable. It uses English words frequently whereas other languages use punctuation, and it has
fewer syntactic constructions than other languages.
● Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to
compile your program before executing it. This is similar to PERL and PHP.
● Python is Interactive − You can actually sit at a Python prompt and interact with the interpreter
directly to write your programs.
● Python is Object-Oriented − Python supports the Object-Oriented style or technique of
programming that encapsulates code within objects.
● Python is a Beginner's Language − Python is a great language for the beginner-level programmers
and supports the development of a wide range of applications from simple text processing to WWW
browsers to games.
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.
● Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68,
SmallTalk, and Unix shell and other scripting languages.
● Python is copyrighted. Like Perl, Python source code is now available under the GNU General
Public License (GPL).
● 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.
In the above example, the statements that are the same level to the right belong to the function. Generally,
we can use four whitespaces to define indentation.
Python Features
Python's features include −
● Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This
allows the student to pick up the language quickly.
● Easy-to-read − Python code is more clearly defined and visible to the eyes.
● Easy-to-maintain − Python's source code is fairly easy-to-maintain.
1
RNGPIT Introduction to Python Programming
● A broad standard library − Python's bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
● Interactive Mode − Python has support for an interactive mode which allows interactive testing and
debugging of snippets of code.
● Portable − Python can run on a wide variety of hardware platforms and has the same interface on all
platforms.
● Extendable − You can add low-level modules to the Python interpreter. These modules enable
programmers to add to or customize their tools to be more efficient.
● Databases − Python provides interfaces to all major commercial databases.
● GUI Programming − Python supports GUI applications that can be created and ported to many
system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window
system of Unix.
● Scalable − Python provides a better structure and support for large programs than shell scripting.
Apart from the above-mentioned features, Python has a big list of good features, few are listed below −
● It supports functional and structured programming methods as well as OOP.
● It can be used as a scripting language or can be compiled to byte-code for building large applications.
● It provides very high-level dynamic data types and supports dynamic type checking.
● It supports automatic garbage collection.
● It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
Go to the command line prompt and type “python” then press enter key. If there is a response from a Python
interpreter we can understand that Python is already installed and it would show a version number in its
display. If there is no response about Python and it’s version number then we need to follow the guidelines
below to install Python. These steps are applicable if you may want to install a new version as well.
2
RNGPIT Introduction to Python Programming
● Download Windows x86-64 executable installer (this is for 64-bit operating system) and
● Download Windows x86 executable installer (this is for 32-bit operating system).
3
RNGPIT Introduction to Python Programming
Click the link that corresponds to your operating system and download the installer onto your computer.
Once the download is complete, run it by double-clicking the installer file. In the installation process,
select Install now option. It will show the default location where Python is going to be installed. Please make
sure that Add to path checkbox is selected. This will add Python in the system Path variable. Operating
systems check the contents of the path variable to see the installation directory of a software application or
language.
Once Python is included in the path variable, we can run Python from any directory. By default, we can run
Python only from the directory where it’s installed.
4
RNGPIT Introduction to Python Programming
5
RNGPIT Introduction to Python Programming
Now as mentioned earlier let us create a hello.py and run python program using the command python
hello.py. You will see the output “Hello Python” on the screen.
If you want to try Python online without installing Python on your computer, there are many online
interpreters available on the internet with limited features.
6
RNGPIT Introduction to Python Programming
● Data Science
● Date Mining
● Desktop Applications
● Console-based Applications
● Mobile Applications
● Software Development
● Artificial Intelligence
● Web Applications
● Enterprise Applications
● 3D CAD Applications
● Machine Learning
● Computer Vision or Image Processing Applications.
● Speech Recognitions
Python has wide range of libraries and frameworks widely used in various fields such as machine learning,
artificial intelligence, web applications, etc. We define some popular frameworks and libraries of Python as
follows.
Invoking the interpreter without passing a script file as a parameter brings up the following prompt −
7
RNGPIT Introduction to Python Programming
Type the following text at the Python prompt and press the Enter –
If you are running new version of Python, then you would need to use print statement with parenthesis as in
print ("Hello, Python!"); However in Python version 2.4.3, this produces the following result −
We assume that you have Python interpreter set in PATH variable. Now, try to run this program as follows –
Let us try another way to execute a Python script. Here is the modified test.py file
We assume that you have Python interpreter available in /usr/bin directory. Now, try to run this program as
follows –
8
RNGPIT Introduction to Python Programming
Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module or other object. An
identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters,
underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a case
sensitive programming language. Thus, Manpower and manpower are two different identifiers in Python.
Here are naming conventions for Python identifiers −
● Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
● Starting an identifier with a single leading underscore indicates that the identifier is private.
● Starting an identifier with two leading underscores indicates a strongly private identifier.
● If the identifier also ends with two trailing underscores, the identifier is a language-defined special
name.
Reserved Words
The following list shows the Python keywords. These are reserved words and you cannot use them as
constant or variable or any other identifier names. All the Python keywords contain lowercase letters only.
9
RNGPIT Introduction to Python Programming
Thus, in Python all the continuous lines indented with same number of spaces would form a block. The
following example has various statement blocks −
Note − Do not try to understand the logic at this point of time. Just make sure you understood various blocks
even if they are without braces.
10
RNGPIT Introduction to Python Programming
Multi-Line Statements
Statements in Python typically end with a new line. Python does, however, allow the use of the line
continuation character (\) to denote that the line should continue. For example –
Statements contained within the [], {}, or () brackets do not need to use the line continuation character. For
example –
Quotation in Python
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the same
type of quote starts and ends the string.
The triple quotes are used to span the string across multiple lines. For example, all the following are legal –
Comments in Python
A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the
end of the physical line are part of the comment and the Python interpreter ignores them.
You can type a comment on the same line after a statement or expression –
11
RNGPIT Introduction to Python Programming
Following triple-quoted string is also ignored by Python interpreter and can be used as a multiline
comments:
The variable a holds integer value five and we did not define its type. Python interpreter will automatically
interpret variables a as an integer type.
Python enables us to check the type of the variable used in the program. Python provides us the type()
function, which returns the type of the variable passed.
Consider the following example to define the values of different data types and checking its type.
Output:
12
RNGPIT Introduction to Python Programming
Numbers
Number stores numeric values. The integer, float, and complex values belong to a Python Numbers
data-type. Python provides the type() function to know the data-type of the variable. Similarly, the
isinstance() function is used to check an object belongs to a particular class.
Python creates Number objects when a number is assigned to a variable. For example;
13
RNGPIT Introduction to Python Programming
Output:
Sequence Type
String
The string can be defined as the sequence of characters represented in the quotation marks. In Python, we
can use single, double, or triple quotes to define a string.
String handling in Python is a straightforward task since Python provides built-in functions and operators to
perform operations in the string.
In the case of string handling, the operator + is used to concatenate two strings as the operation "hello"+"
python" returns "hello python".
The operator * is known as a repetition operator as the operation "Python" *2 returns 'Python Python'.
The following example illustrates the string in Python.
Example - 1
Output:
14
RNGPIT Introduction to Python Programming
Example – 2
Output:
List
Python Lists are similar to arrays in C. However, the list can contain data of different types. The items stored
in the list are separated with a comma (,) and enclosed within square brackets [].
We can use slice [:] operators to access the data of the list. The concatenation operator (+) and repetition
operator (*) works with the list in the same way as they were working with the strings.
Consider the following example.
15
RNGPIT Introduction to Python Programming
Output:
Tuple
A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the items of
different data types. The items of the tuple are separated with a comma (,) and enclosed in parentheses ().
A tuple is a read-only data structure as we can't modify the size and value of the items of a tuple.
Let's see a simple example of the tuple.
Output:
16
RNGPIT Introduction to Python Programming
Dictionary
Dictionary is an unordered set of a key-value pair of items. It is like an associative array or a hash table
where each key stores a specific value. Key can hold any primitive data type, whereas value is an arbitrary
Python object.
The items in the dictionary are separated with the comma (,) and enclosed in the curly braces {}.
Consider the following example.
Output:
Boolean
Boolean type provides two built-in values, True and False. These values are used to determine the given
statement true or false. It denotes by the class bool. True can be represented by any non-zero value or 'T'
whereas false can be represented by the 0 or 'F'. Consider the following example.
Output:
17
RNGPIT Introduction to Python Programming
Set
Python Set is the unordered collection of the data type. It is iterable, mutable(can modify after creation), and
has unique elements. In set, the order of the elements is undefined; it may return the changed sequence of
the element. The set is created by using a built-in function set(), or a sequence of elements is passed in the
curly braces and separated by the comma. It can contain various types of values. Consider the following
example.
Output:
Python Keywords
Every scripting language has designated words or keywords, with particular definitions and usage
guidelines. Python is no exception. The fundamental constituent elements of any Python program are Python
keywords.
This topic will give you a basic overview of all Python keywords and a detailed discussion of some
important keywords that are frequently used.
18
RNGPIT Introduction to Python Programming
In distinct versions of Python, the preceding keywords might be changed. Some extras may be introduced,
while others may be deleted. By writing the following statement into the coding window, you can anytime
retrieve the collection of keywords in the version you are working on.
Python Operators
Python Operators in general are used to perform operations on values and variables. These are standard
symbols used for the purpose of logical and arithmetic operations. In this unit, we will look into different
types of Python operators.
OPERATORS: Are the special symbols. Eg- + , * , /, etc.
OPERAND: It is the value on which the operator is applied.
Arithmetic Operators
Arithmetic operators are used to performing mathematical operations like addition, subtraction,
multiplication, and division.
In Python 3.x the result of division is a floating-point while in Python 2.x division of 2 integers is an integer
and to obtain an integer result in Python 3.x floored (// integer) is used.
19
RNGPIT Introduction to Python Programming
20
RNGPIT Introduction to Python Programming
Output:
Comparison Operators
Comparison of Relational operators compares the values. It either returns True or False according to the
condition.
21
RNGPIT Introduction to Python Programming
Output:
22
RNGPIT Introduction to Python Programming
Logical Operators
Logical operators perform Logical AND, Logical OR, and Logical NOT operations. It is used to combine
conditional statements.
Output:
23
RNGPIT Introduction to Python Programming
Bitwise Operators
Bitwise operators act on bits and perform the bit-by-bit operations. These are used to operate on binary
numbers.
Output:
24
RNGPIT Introduction to Python Programming
Assignment Operators
Assignment operators are used to assign values to the variables.
Output:
25
RNGPIT Introduction to Python Programming
Identity Operators
is and is not are the identity operators both are used to check if two values are located on the same part of
the memory. Two variables that are equal do not imply that they are identical.
Output:
Membership Operators:
in and not in are the membership operators used to test whether a value or variable is in a sequence.
Output:
26
RNGPIT Introduction to Python Programming
The following table lists all operators from highest precedence to lowest.
27
RNGPIT Introduction to Python Programming
28
RNGPIT Introduction to Python Programming
Output:
When you execute the above program, it produces the following result −
Python Variables:
● Variable is a name that is used to refer to memory location. Python variable is also known as an
identifier and used to hold value.
● In Python, we don't need to specify the type of variable because Python is a infer language and smart
enough to get variable type.
● Variable names can be a group of both the letters and digits, but they have to begin with a letter or an
underscore.
● It is recommended to use lowercase letters for the variable name. Rahul and rahul both are two
different variables.
29
RNGPIT Introduction to Python Programming
The variable b refers to the same object that a points to because Python does not create another object.
Let's assign the new value to b. Now both variables will refer to the different objects.
Python manages memory efficiently if we assign the same variable to two different values.
30
RNGPIT Introduction to Python Programming
Pascal Case:
It is the same as the Camel Case, but here the first word is also capital. For example - NameOfStudent, etc.
Snake Case:
In the snake case, Words are separated by the underscore. For example - name_of_student, etc.
Multiple Assignment:
Python allows us to assign a value to multiple variables in a single statement, which is also known as
multiple assignments.
We can apply multiple assignments in two ways, either by assigning a single value to multiple variables or
assigning multiple values to multiple variables.
Consider the following example.
Assigning single value to multiple variables
31
RNGPIT Introduction to Python Programming
Variable Types:
There are two types of variables in Python - Local variable and Global variable.
● Local Variable
● Global Variables
Local Variable:
Local variables are the variables that are declared inside the function and have scope within the function.
------------
# Declaring a function
def add():
# Defining local variables. They has scope only within a function
a = 20
b = 30
32
RNGPIT Introduction to Python Programming
c=a+b
print("The sum is:", c)
# Calling a function
add()
#print(a)
------------
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.
If we try to use them outside the function, we will get the error.
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 the global variable inside the function.
● If we don't use the global keyword, the function treats it as a local variable.
Example:
# Declare a variable and initialize it
x = 100
# Global variable in function
def mainFunction():
# printing a global variable
global x
print(x)
# modifying a global variable
x = 'Welcome To Pythonclub'
print(x)
mainFunction()
print(x)
33
RNGPIT Introduction to Python Programming
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 newly assigned value of x.
Delete a variable
We can delete the variable using the del keyword. The syntax is given below.
del <variable_name>
# Assigning a value to x
x=6
print(x)
# deleting a variable.
del x
print(x)
34
RNGPIT Introduction to Python Programming
In Python, a string is a sequence of Unicode characters. Unicode was introduced to include every character
in all languages and bring uniformity in encoding. You can learn about Unicode from Python Unicode.
35
RNGPIT Introduction to Python Programming
If we try to access an index out of the range or use numbers other than an integer, we will get errors.
Slicing can be best visualized by considering the index to be between the elements as shown below.
If we want to access a range, we need the index that will slice the portion from the string.
We cannot delete or remove characters from a string. But deleting the string entirely is possible using the del
keyword.
36
RNGPIT Introduction to Python Programming
Writing two string literals together also concatenates them like + operator.
If we want to concatenate strings in different lines, we can use parentheses.
37
RNGPIT Introduction to Python Programming
38
RNGPIT Introduction to Python Programming
Output:
39
RNGPIT Introduction to Python Programming
For more string methods examples, visit: Python String Methods - Learn By Example
Expressions in Python
An expression is a combination of operators and operands that is interpreted to produce some other value. In
any programming language, an expression is evaluated as per the precedence of its operators. So that if there
is more than one operator in an expression, their precedence decides which operation will be performed first.
We have many different types of expressions in Python.
1. Constant Expressions:
These are the expressions that have constant values only.
Example:
Output:
2. Arithmetic Expressions:
An arithmetic expression is a combination of numeric values, operators, and sometimes parenthesis.
The result of this type of expression is also a numeric value. The operators used in these expressions
are arithmetic operators like addition, subtraction, etc.
Here are some arithmetic operators in Python:
Example:
40
RNGPIT Introduction to Python Programming
Output:
3. Integral Expressions:
These are the kind of expressions that produce only integer results after all computations and type
conversions.
Example:
Output:
4. Floating Expressions:
These are the kind of expressions which produce floating point numbers as a result after all
computations and type conversions.
Example:
41
RNGPIT Introduction to Python Programming
Output:
5. Relational Expressions:
In these types of expressions, arithmetic expressions are written on both sides of relational operator
(> , < , >= , <=). Those arithmetic expressions are evaluated first, and then compared as per
relational operator and produce a boolean output in the end. These expressions are also called
Boolean expressions.
Example:
Output:
6. Logical Expressions:
These are kinds of expressions that result in either True or False. It basically specifies one or more
conditions. For example, (10 == 9) is a condition if 10 is equal to 9. As we know it is not correct, so
it will return False. Studying logical expressions, we also come across some logical operators which
can be seen in logical expressions most often. Here are some logical operators in Python:
Example:
42
RNGPIT Introduction to Python Programming
Output:
7. Bitwise Expressions:
These are the kind of expressions in which computations are performed at bit level.
Example:
Output:
8. Combinational Expressions:
We can also use different types of expressions in a single expression, and that will be termed as
combinational expressions.
Example:
Output:
43
RNGPIT Introduction to Python Programming
So, if we have more than one operator in an expression, it is evaluated as per operator precedence.
For example, if we have the expression “10 + 3 * 4”. Going without precedence it could have given
two different outputs: 22 or 52. But now looking at operator precedence, it must yield 22. Let’s
discuss this with the help of a Python program:
44
RNGPIT Introduction to Python Programming
Output:
Hence, operator precedence plays an important role in the evaluation of a Python expression.
Here we write a command and to execute the command just press the enter key and your command will be
interpreted.
For coding in Python you must know the basics of the console used in Python.
The primary prompt of the python console is the three greater than symbols
You are free to write the next command on the shell only when after executing the first command these
prompts have appeared. The Python Console accepts command in Python which you write after the prompt.
45
RNGPIT Introduction to Python Programming
We can also typecast this input to integer, float or string by specifying the input() function inside the type.
1. Typecasting the input to Integer: There might be conditions when you might require integer input
from user/Console, the following code takes two input(integer/float) from console and typecasts
them to integer then prints the sum.
2. Typecasting the input to Float: To convert the input to float the following code will work out.
3. Typecasting the input to String: All kinds of input can be converted to string type whether they are
float or integer. We make use of the keyword str for typecasting.
Output:
2. Tuple assignment:
Output:
When we code a tuple on the left side of the =, Python pairs objects on the right side with targets on
the left by position and assigns them from left to right. Therefore, the values of x and y are 50 and
100 respectively.
3. List assignment:
This works in the same way as the tuple assignment.
Output:
47
RNGPIT Introduction to Python Programming
4. Sequence assignment:
In recent versions of Python, tuple and list assignment have been generalized into instances of what
we now call sequence assignment – any sequence of names can be assigned to any sequence of
values, and Python assigns the items one at a time by position.
Output:
Here, p is matched with the first character in the string on the right and q with the rest. The starred
name (*q) is assigned a list, which collects all items in the sequence not assigned to other names.
Output:
This is especially handy for a common coding pattern such as splitting a sequence and accessing its
front and rest part.
Output:
48
RNGPIT Introduction to Python Programming
In this form, Python assigns a reference to the same object (the object which is rightmost) to all the
target on the left.
Output:
7. Augmented assignment:
The augmented assignment is a shorthand assignment that combines an expression and an
assignment.
Output:
Discussion
Lvalue and Rvalue refer to the left and right side of the assignment operator. The Lvalue (pronounced: L
value) concept refers to the requirement that the operand on the left side of the assignment operator is
modifiable, usually a variable. Rvalue concept pulls or fetches the value of the expression or operand on the
right side of the assignment operator. Some examples:
49
RNGPIT Introduction to Python Programming
The value 39 is pulled or fetched (Rvalue) and stored into the variable named age (Lvalue); destroying the
value previously stored in that variable.
If the expression has a variable or named constant on the right side of the assignment operator, it will pull or
fetch the value stored in the variable or constant. The value 18 is pulled or fetched from the variable named
voting_age and stored into the variable named age.
If the expression is a test expression or Boolean expression, the concept is still an Rvalue one. The value in
the identifier named age is pulled or fetched and used in the relational comparison of less than.
This is illegal because the identifier JACK_BENNYS_AGE does not have value properties. It is not a
modifiable data object, because it is a constant.
Some uses of the Lvalue and Rvalue can be confusing in languages that support increment and decrement
operators. Consider:
Postfix increment says to use my existing value then when you are done with the other operators; increment
me. Thus, the first use of the oldest variable is an Rvalue context where the existing value of 55 is pulled or
fetched and then assigned to the variable age; an Lvalue context. The second use of the oldest variable is an
Lvalue context wherein the value of the oldest is incremented from 55 to 56.
Key Terms
Lvalue
The requirement that the operand on the left side of the assignment operator is modifiable, usually a
variable.
Rvalue
Pulls or fetches the value stored in a variable or constant.
50
RNGPIT Introduction to Python Programming
● Interactive mode
● Script mode
Interactive Mode
Interactive mode, also known as the REPL provides us with a quick way of running blocks or a
single line of Python code. The code executes via the Python shell, which comes with the Python
installation. Interactive mode is handy when you just want to execute basic Python commands or you
are new to Python programming and just want to get your hands dirty with this beautiful language.
To access the Python shell, open the terminal of your operating system and then type "python". Press
the enter key and the Python shell will appear. This is the same Python executable you use to execute
scripts, which comes installed by default on Mac and Unix-based operating systems.
The >>> indicates that the Python shell is ready to execute and send your commands to the Python
interpreter. The result is immediately displayed on the Python shell as soon as the Python interpreter
interprets the command.
To run your Python statements, just type them and hit the enter key. You will get the results
immediately, unlike in script mode. For example, to print the text "Hello World", we can type the
following:
We can also run multiple statements on the Python shell. A good example of this is when we need to
declare many variables and access them later. This is demonstrated below:
Output
51
RNGPIT Introduction to Python Programming
Using the method demonstrated above, you can run multiple Python statements without having to
create and save a script. You can also copy your code from another source then paste it on the Python
shell.
Consider the following example:
The above example also demonstrates how we can run multiple Python statements in interactive
mode. The two print statements have been indented using four spaces. Just like in script mode, if you
don't indent properly you will get an error. Also, to get the output after the last print statement, you
should press the enter key twice without typing anything.
Pros and Cons of Interactive Mode:
The following are the advantages of running your code in interactive mode:
1. Helpful when your script is extremely short and you want immediate results.
2. Faster as you only have to type a command and then press the enter key to get the results.
3. Good for beginners who need to understand Python basics.
The following are the disadvantages of running your code in the interactive mode:
1. Editing the code in interactive mode is hard as you have to move back to the previous
commands or else you have to rewrite the whole command again.
2. It's very tedious to run long pieces of code.
Script Mode
If you need to write a long piece of Python code or your Python script spans multiple files,
interactive mode is not recommended. Script mode is the way to go in such cases. In script mode,
You write your code in a text file then save it with a .py extension which stands for "Python". Note
that you can use any text editor for this, including Sublime, Atom, notepad++, etc.
If you are in the standard Python shell, you can click "File" then choose "New" or simply hit "Ctrl +
N" on your keyboard to open a blank script in which you can write your code. You can then press
"Ctrl + S" to save it.
After writing your code, you can run it by clicking "Run" then "Run Module" or simply press F5.
Let us create a new file from the Python shell and give it the name "hello.py". We need to run the
"Hello World" program. Add the following code to the file:
Click "Run" then choose "Run Module". This will run the program:
52
RNGPIT Introduction to Python Programming
Other than executing the program from the graphical user interface, we can do it from the terminal of
the operating system. However, you must be aware of the path to the directory where you have saved
the file.
Open the terminal of your operating system then navigate to the location of the file. Of course, you
will use the "cd (change directory)" command for this.
Once you reach the directory with the file, you will need to invoke the Python interpreter on the file.
This can be done using the following syntax:
To run the Python file from the terminal, you just have to type the python keyword followed by the
name of the file. In our case, we need to run a file named "hello.py". We need to type the following
on the terminal of the operating system:
If you want to get to the Python shell after getting the output, add the -i option to the command. This
is demonstrated below:
The following example demonstrates how to execute the multiple lines of code using the Python
script.
53
RNGPIT Introduction to Python Programming
Mutable Definition
Mutable is when something is changeable or has the ability to change. In Python, ‘mutable’ is the ability of
objects to change their values. These are often the objects that store a collection of data.
Immutable Definition
Immutable is the when no change is possible over time. In Python, if the value of an object cannot be
changed over time, then it is known as immutable. Once created, the value of these objects is permanent.
54
RNGPIT Introduction to Python Programming
Objects in Python
In Python, everything is treated as an object. Every object has these three attributes:
Identity – This refers to the address that the object refers to in the computer’s memory.
Type – This refers to the kind of object that is created. For example- integer, list, string etc.
Value – This refers to the value stored by the object. For example – List=[1,2,3] would hold the numbers 1,2
and 3
While ID and Type cannot be changed once it’s created, values can be changed for Mutable objects.
# Printing the elements from the list cities, separated by a comma & space
#Printing the location of the object created in the memory address in hexadecimal format
#Printing the elements from the list cities, separated by a comma & space
55
RNGPIT Introduction to Python Programming
#Printing the location of the object created in the memory address in hexadecimal format
The above example shows us that we were able to change the internal state of the object ‘cities’ by adding
one more city ‘Chennai’ to it, yet, the memory address of the object did not change. This confirms that we
did not create a new object, rather, the same object was changed or mutated. Hence, we can say that the
object which is a type of list with reference variable name ‘cities’ is a MUTABLE OBJECT.
#Printing the location of the object created in the memory address in hexadecimal format
#tuples are immutable, so you cannot add new elements, hence, using merge of tuples with the # + operator
to add a new imaginary day in the tuple ‘weekdays’
#Printing the location of the object created in the memory address in hexadecimal format
56
RNGPIT Introduction to Python Programming
This above example shows that we were able to use the same variable name that is referencing an object
which is a type of tuple with seven elements in it. However, the ID or the memory location of the old & new
tuple is not the same. We were not able to change the internal state of the object ‘weekdays’. The Python
program manager created a new object in the memory address and the variable name ‘weekdays’ started
referencing the new object with eight elements in it. Hence, we can say that the object which is a type of
tuple with reference variable name ‘weekdays’ is an IMMUTABLE OBJECT.
57
RNGPIT Introduction to Python Programming
58