0% found this document useful (0 votes)
98 views57 pages

Python Notes Complete UNIT - I

Uploaded by

ameenabegum84162
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
98 views57 pages

Python Notes Complete UNIT - I

Uploaded by

ameenabegum84162
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 57

PYTHON PROGRAMMING

A programming language is a formal computer language or constructed


language designed to communicate instructions to a machine, particularly a
computer. Programming languages can be used to create programs to control the
behavior of a machine or to express algorithms.

INTRODUCTION OF PYTHON
➢ Python is an object-oriented, high level language, interpreted, dynamic and
multipurpose programming language.
➢ Python is easy to learn yet powerful and versatile scripting language which makes
it attractive for Application Development.
➢ Python's syntax and dynamic typing with its interpreted nature, make it an ideal
language for scripting and rapid application development in many areas.
➢ Python supports multiple programming pattern, including object-oriented
programming, imperative and functional programming or procedural styles.
➢ Python is not intended to work on special area such as web programming. That
is why it is known as multipurpose because it can be used with web, enterprise,
3D CAD etc.
➢ We don't need to use data types to declare variable because it is dynamically
typed so we can write a=10 to declare an integer value in a variable.
➢ Python makes the development and debugging fast because there is no
compilation step included in python development and edit-test-debug cycle is
very fast.
➢ It is used for GUI and database programming, client- and server-side web
programming, and application testing.
➢ It is used by scientists writing applications for the world's fastest supercomputers
and by children first learning to program.

BSC -VI Python_Programming (GUG) 1


HISTORY OF PYTHON
Python was conceptualized by Guido Van Rossum in the late 1980s. Rossum
published the first version of Python code (0.9.0) in February 1991 at the CWI
(Centrum Wiskunde & Informatica) in the Netherlands, Amsterdam. Python is
derived from ABC programming language, which is a general-purpose programming
language that had been developed at the CWI. Rossum chose the name "Python",
since he was a big fan of Monty Python's Flying Circus. Python is now maintained
by a core development team at the institute, although Rossum still holds a vital role
in directing its progress.

COMPILER vs INTERPRETER

• An interpreter is a program that reads and executes code. This includes source
code, pre-compiled code, and scripts. Common interpreters include Perl, Python,
and Ruby interpreters, which execute Perl, Python, and Ruby code respectively.
• Interpreters and compilers are similar, since they both recognize and process
source code.
• However, a compiler does not execute the code like and interpreter does. Instead,
a compiler simply converts the source code into machine code, which can be run
directly by the operating system as an executable program.
• Interpreters bypass the compilation process and execute the code directly.
• Interpreters are commonly installed on Web servers, which allows developers to
run executable scripts within their webpages. These scripts can be easily edited
and saved without the need to recompile the code. Without an interpreter, the
source code serves as a plain text file rather than an executable program.

PREPARED BY:MRA BSC -VI Python_Programming (GUG) 2


PYTHON VERSIONS

• Python 1.0
• Python 2.0
• Python 3.0

BSC -VI Python_Programming (GUG) 3


PYTHON FEATURES

❖ Easy to learn, easy to read and easy to maintain.


❖ Portable: It can run on various hardware platforms and has the same interface
on all platforms.
❖ Extendable: You can add low-level modules to the Python interpreter.
❖ Scalable: Python provides a good structure and support for large programs.
Python has support for an interactive mode of testing and debugging.
❖ Python has a broad standard library cross-platform.
❖ Everything in Python is an object: variables, functions, even code. Every object
has an ID, a type, and a value.
❖ Python provides interfaces to all major commercial databases.
❖ Python supports functional and structured programming methods as well as
OOP.
❖ Python provides very high-level dynamic data types and supports dynamic type
P R E P A R E D B Y : M R A
checking.
❖ Python supports GUI applications
❖ Python supports automatic garbage collection.
❖ Python can be easily integrated with C, C++, and Java.

PYTHON VIRTUAL MACHINE (PVM) OR INTERPRETER

Python converts the source code into byte code. Byte code represents the fixed
set of instructions created by Python developers representing all types of operations.
The size of each byte code instruction is 1 byte.

BSC -VI Python_Programming (GUG) 4


The role of PVM is to convert the byte code instructions into machine code.
So that the computer can execute those machine code instruction and display the
final output. The PVM is also called as interpreter.

Python Shell

Python Interpreter is a program which translates your code into machine


language and then executes it line by line.

We can use Python Interpreter in two modes:

1. Interactive Mode.

2. Script Mode.

In Interactive Mode, Python interpreter waits for you to enter command.


When you type the command, Python interpreter goes ahead and executes the
command, then it waits again for your next command.

In Script mode, Python Interpreter runs a program from the source file.

APPLICATIONS OF PYTHON
✓ Machine Learning
✓ GUI Applications (like Kivy, Tkinter, PyQt etc. )
✓ Web frameworks like Django (used by YouTube, Instagram, Dropbox)
✓ Image processing (like OpenCV, Pillow)
✓ Web scraping (like Scrapy, BeautifulSoup, Selenium)
✓ Test frameworks
✓ Multimedia
✓ Scientific computing
✓ Text processing

BSC -VI Python_Programming (GUG) 5


P R E P A R E D B Y : M R A

STRUCTURE OF A PYTHON PROGRAM

Python Statements
In general, the interpreter reads and executes the statements line by line i.e.
sequentially. Though, there are some statements that can alter this behavior like
conditional statements. Mostly, python statements are written in such a format that
one statement is only written in a single line. The interpreter considers the ‘new line
character’ as the terminator of one instruction.

Example 1:
print('Welcome to Geeks for Geeks')

Instructions that a Python interpreter can execute are called statements. For example,
a = 1 is an assignment statement.
if statement,
for statement,
while statement etc.

Multi-line statement

In Python, end of a statement is marked by a newline character. But we can


make a statement extend over multiple lines with the line continuation character (\).

For example:
a=1+2+3+\
4+5+6+\
7+8+9

BSC -VI Python_Programming (GUG) 6


This is explicit line continuation. In Python, line continuation is implied inside
parentheses ( ), brackets [ ] and braces { }. For instance, we can implement the above
multi-line statement as,

a = (1 + 2 + 3 +
4+5+6+
7 + 8 + 9)

Here, the surrounding parentheses ( ) do the line continuation implicitly. Same is the
case with [ ] and { }.

For example:

colors = ['red',
'blue',
'green']

We could also put multiple statements in a single line using semicolons, as follows:
a = 1; b = 2; c = 3

Python Indentation

Most of the programming languages like C, C++, Java use braces { } to define
a block of code. Python uses indentation.

A code block (body of a function, loop etc.) starts with indentation and ends
with the first unindented line. The amount of indentation is up to you, but it must be
consistent throughout that block.

P R E P A R E D B Y : M R A BSC -VI Python_Programming (GUG) 7


Generally, four whitespaces are used for indentation and is preferred over tabs.

Here is an example.

for i in range(1,11):
print(i)
if i == 5:
break
The enforcement of indentation in Python makes the code look neat and clean.
This results into Python programs that look similar and consistent.

Indentation can be ignored in line continuation. But it's a good idea to always
indent. It makes the code more readable.

For example:

if True:
print('Hello')
a=5
and
if True: print('Hello'); a = 5

Both are valid and do the same thing. But the former style is clearer. Incorrect
indentation will result into IndentationError.

Python Comments
Comments are very important while writing a program. It describes what's
going on inside a program so that a person looking at the source code does not have
a hard time figuring it out. You might forget the key details of the program you just
wrote in a month's time. So taking time to explain these concepts in form of
comments is always fruitful.

BSC -VI Python_Programming (GUG) 8


In Python, we use the hash (#) symbol to start writing a comment.
It extends up to the newline character. Comments are for programmers for better
understanding of a program. Python Interpreter ignores comment.

#This is a comment
#print out Hello
print('Hello')

Multi-line comments
If we have comments that extend multiple lines, one way of doing it is to use
hash (#) in the beginning of each line.

For example:

#This is a long comment


#and it extends
#to multiple lines
Another way of doing this is to use triple quotes, either ''' or """.

These triple quotes are generally used for multi-line strings. But they can be
used as multi-line comment as well. Unless they are not docstrings, they do not
generate any extra code.

"""This is also a
perfect example of
multi-line comments"""

BSC -VI Python_Programming (GUG) 9


P R E P A R E D B Y : M R A

INPUT AND OUTPUT STATEMENTS

Input Statement:
Input means the data entered by the user of the program. In python, we have
input() and raw_input ( ) function available for Input.

1) input () function

Syntax:
input (expression)

If prompt is present, it is displayed on monitor, after which the user can


provide data from keyboard. Input takes whatever is typed from the keyboard and
evaluates it. As the input provided is evaluated, it expects valid python expression.
If the input provided is not correct then either syntax error or exception is raised by
python.

P R E P A R E D B Y : M R A

BSC -VI Python_Programming (GUG) 10


P R E P A R E D B Y : M R A

BSC -VI Python_Programming (GUG) 11


Output Statement:

1). print () function/statement


print evaluates the expression before printing it on the monitor. Print
statement outputs an entire (complete) line and then goes to next line for subsequent
output (s). To print more than one item on a single line, comma (,) may be used.

Syntax:
print (expression/constant/variable)

BSC -VI Python_Programming (GUG) 12


Print function

The print a line of text, and then the cursor moves down to the next line so any future
printing appears on the next line.

print('enter an integer value:')

The print statement accepts an additional argument that allows the cursor to remain
on the same line as the printed text:

print('enter an integer value:', end=' ')

The expression end=' ' is the keyword that cause the cursor to remain on the same
line as the printed text. Without this keyword argument, the cursor moves down to
the next line after printing the text.

The statement print ('enter an integer value:', end='\n') that is, the default ending for
a line of printed text is the string '\n', the newline control code. Similarly,

The statement print() is a shorter way to express print(end='\n')


By default, the print function places a single space in between the items it prints.

Print uses
keyword arguments named sep to specify the string to use insert between
items. The name sep stands for separator. The default value of sep is the string ' ',
containing single space.
The program sep.py shows the sep keyword customizes print’s behavior.

BSC -VI Python_Programming (GUG) 13


VARIABLES:

Variables are nothing but reserved memory locations to store values. This
means that when you create a variable you reserve some space in memory.

Based on the data type of a variable, the interpreter allocates memory and
decides what can be stored in the reserved memory. Therefore, by assigning different
data types to variables, you can store integers, decimals or characters in these
variables.

Rules for Python variables:

➢ A variable name must start with a letter or the underscore character


➢ A variable name cannot start with a number
➢ A variable name can only contain alpha-numeric characters and underscores (A-
z, 0-9, and _) P R E P A R E D B Y : M R A

➢ Variable names are case-sensitive (age, Age and AGE are three different
variables)

Assigning Values to Variables:

Python variables do not need explicit declaration to reserve memory space.


The declaration happens automatically when you assign a value to a variable. The
equal sign (=) is used to assign values to variables.

The operand to the left of the = operator is the name of the variable and the operand
to the right of the = operator is the value stored in the variable.
Every value in Python has a datatype. Different data types in Python are Numbers,
List, Tuple, Strings, Dictionary, etc. Variables can be declared by any name or even
alphabets like a, aa, abc, etc.

BSC -VI Python_Programming (GUG) 14


How to Declare and use a Variable

Let see an example. We will declare variable "a" and print it.
a=100
print a

For example:-
a= 100 # An integer assignment
b = 1000.0 # A floating point
c = "John" # A string
print (a)
print (b)
print (c)
This produces the following result −
100
1000.0
John

Multiple Assignment:

Python allows you to assign a single value to several variables simultaneously.

For example:-01

a=b=c=1

Here, an integer object is created with the value 1, and all three variables are assigned
to the same memory location. You can also assign multiple objects to multiple
variables.
For example :-02

a, b, c = 1,2,"madhu “

Here, two integer objects with values 1 and 2 are assigned to variables a and b
respectively, and one string object with the value "john" is assigned to the variable
c.

Output Variables:

The Python print statement is often used to output variables.

BSC -VI Python_Programming (GUG) 15


Variables do not need to be declared with any particular type and can even change
type after they have been set.

x=5 # x is of type int


x = "madhu " # x is now of type str
print(x)

Output: madhu

To combine both text and a variable, Python uses the “+” character:
Example: -01

x = "awesome"
print("Python is " + x)

Output
Python is awesome
You can also use the + character to add a variable to another variable:

Example: -02

x = "Python is "
y = "awesome"
z=x+y
print(z)

Output:
Python is awesome

List of some different variable types


x = 123 # integer
x = 123L # long integer
x = 3.14 # double float
x = "hello" # string
x = [0,1,2] # list
x = (0,1,2) # tuple
x = open (‘hello.py’, ‘r’) # file

BSC -VI Python_Programming (GUG) 16


CONSTANT:

A constant is a type of variable whose value cannot be changed. It is helpful


to think of constants as containers that hold information which cannot be changed
later.

Non-technically, you can think of constant as a bag to store some books and those
books cannot be replaced once place inside the bag.

Assigning value to a constant in Python: -

In Python, constants are usually declared and assigned on a module. Here, the
module means a new file containing variables, functions etc which is imported to
main file. Inside the module, constants are written in all capital letters and
underscores separating the words.

BSC -VI Python_Programming (GUG) 17


P R E P A R E D B Y : M R A
DATA TYPES:

A data type represents the type of data stored into a variable or memory.
There are 5 different data types are:

1) None type
2) Numeric type
3) Sequences
4) Sets
5) Dictionary

1) None data type:

The none data type represents an object that does not contain any value. In java
language it is called “NULL” object. But in Python it is called as “none”. In Python
maximum of only one ‘none’ object is provided. If no value is passed to the function,
then the default value will be taken as ‘none’.

2) Numeric data type:

The numeric type represents numbers. There are 3 sub types:

✓ int
✓ float
✓ complex

BSC -VI Python_Programming (GUG) 18


✓ int data type:

The int data type represents integer number (Whole number). An integer number
is number without fraction. Integers can be of any length, it is only limited by the
memory available.

E.g. a = 10
b = -29

✓ float data type:

The float data type represents floating point number. A floating-point number is
a number with fraction. Floating point numbers can also be written in scientific
notation using exponentiation format.

A floating-point number is accurate up to 15 decimal places. Integer and floating


points are separated by decimal points.

E.g. c = 2.0
d = -29.45
x = 2.5E4

✓ complex data type:

A complex number is number is written in the form of x +yj or x+yJ. Here x is


the real part and y is the imaginary part.

E.g. a= 5 +6j
b= 2.5 + 6.2J
We can use the type() function to know which class a variable or a value
belongs to and the isinstance() function to check if an object belongs to a particular
class.

BSC -VI Python_Programming (GUG) 19


EX:
a=5
print(a, "is of type", type(a))
b = 2.0
print(a, "is of type", type(b))
c = 1+2j
print(c, "is complex number?", isinstance(c.complex))

3) Sequences:
A sequence represents a group of items or elements. There are six types of
sequences in Python. Important sequences as follows,
✓ Str
✓ list
✓ tuple

✓ str data type :


The str represents string data type. A string is a collection of character enclosed
in single or double quotes. Both are valid.

E.g. str=”madhu” # str is name of string variable


str=’madhu’ # str is name of string variable

Triple double quote or triple single quotes are used to embed a string in a
another string (Nested string).

str=”””This is ‘str data type’ example”””


print(str) # output is : This is ‘str data type’ example
str=’’’ This is “str data type” example’’’
print(str) # output is : This is “str data type” example

BSC -VI Python_Programming (GUG) 20


The [] operator used to retrieve specified character from the string. The string index
starts from 0. Hence, str [0] indicates the 0th character in the string.

e.g
str= “madhu gfgcr”
print(str) # it display - madhu gfgcr
print(str[0]) # it display - m
print(str[4]) # it display –u
print(str[2:4]) # it display 2nd to 4th character – dh
print(str[-1]) # it display first character from end – r

✓ list data type:

A List is a collection which is ordered and changeable. It allows duplicate


members. A list is similar to array. Lists are represented by square brackets [] and
the elements are separated by comma.

The main difference between a list and an array is that a list can store different
data type elements, but an array can store only one type of elements. List can also
grow dynamically in memory but the size of array is fixed and they cannot grow
dynamically.

e.g.
list=[10,3.5,-20, “madhu”,”sudhan”] # create a list
print(list) # it display all elements in the list : 10,3.5,-20,”madhu”,’sudhan’
print(list[0]) # it display : 10
print(list[1:3]) # it display : 3.5, -20.
print(list[-1]) # it display : ‘sudhan’

P R E P A R E D B Y : M R A

BSC -VI Python_Programming (GUG) 21


print(list * 2) # it display :(10, 3.5, -20, “madhu”, ‘sudhan’, 10, 3.5, -20,
“madhu”, ‘sudhan’)
list[1]=1.5 # replace 1st location element by 1.5
print(list) # it display all elements in the list : 10,1.5,-20,”madhu”,’sudhan’

✓ tuple data type:

A tuple is similar to list. A tuple contains group of elements which can be


different types. The elements in the tuple are separated by commas and enclosed in
parentheses ().

The only difference is that tuples are immutable. Tuples once created cannot be
modified. The tuple cannot change dynamically. That means a tuple can be treated
as read-only list.

e.g.
tpl=(10,3.5,-20, “madhu”,”sudhan”) # create a tuple
print(tpl) # it display all elements in the tuple : 10,3.5,-20,”madhu”,’sudhan’
print(tpl[0]) # it display : 10
print(tpl[1:3]) # it display : 3.5, -20
print(tpl[-1]) # it display : ‘sudhan’
tpl[1]=1.5 # replace 1st location element by 1.5

4) Sets:

Set is an unordered collection of unique items and un-indexed. The order of


elements is not maintained in the sets. A set does not accept duplicate elements. Set
is defined by values separated by comma inside braces { }.

BSC -VI Python_Programming (GUG) 22


There are two sub types in sets:
❖ Set data type
❖ Frozen set data type

❖ Set data type:


To create a set, we should enter the elements separated by comma inside a
curly brace.

e.g.
s = {10,30,5, 30,50}
print(s) # it display : {10,5,30,50}

In the above example,


It displays un-orderly and repeated elements only once, because set is
unordered collection and unique items.

We can use set() to create a set as


k=set(“madhu”)
print(k) # it display : {'m', 'd', 'a', 'h', 'u'}

The update() method used to add new elements to a set as


s.update([6,15])
print(s) # it display : {5, 6, 10, 15, 50, 30}

The remove() method used to remove a particular element from the set as
s.remove(30)
print(s) # it display: {5, 6, 10, 15, 50}

BSC -VI Python_Programming (GUG) 23


❖ Frozen set data type:
Frozen set is just an immutable version of a Python set object. While elements of
a set can be modified at any time, an element of frozen set remains the same after
creation. Due to this, frozen sets can be used as key in Dictionary or as element of
another set.

5) Dictionary:
A dictionary is an unordered collection, changeable and indexed. In Python
dictionaries are written with curly brackets, and they have keys and values. That
means dictionary contains pair of elements such that first element represents the key
and the next one becomes its value.
The key and value should be separated by a colon(:) and every pair should be
separated by comma. All the elements should be enclosed inside curly brackets.
e.g.
d = {3: ‘madhu’, 4:’rohini’, 5:’laxmi’, 6: ‘sreenika}
Here, d is the name of dictionary. 3 is the key and its associated value is
‘madhu’.
The next is 4 and its value is ‘rohini’ and so on.
print(d) # {3: ‘madhu’, 4:’rohini’, 5:’laxmi’, 6: ‘sreenika}
print(d[5]) # laxmi
print (d.keys()) # dict_keys([3, 4, 5, 6])
print(d.values()) # dict_values(['madhu', 'rohini', 'laxmi', 'srneeika'])
d[2]=’raichur’ # add ‘raichur’ to key value 2
print(d) # {3: 'madhu', 4: 'rohini', 5: 'laxmi', 6: 'srneeika', 2:
'raichur'}
del d[4] # del key 4 and associated value.
print(d) # {3: 'madhu', 5: 'laxmi', 6: 'srneeika', 2: 'raichur'} v

BSC -VI Python_Programming (GUG) 24


PREPARED BY:MRA
is: 1 OPERATORS IN PYTHON:

Operators are special symbols in Python that carry out arithmetic or logical
computation. The value that the operator operates on is called the operand.
Operators are used to perform operations on variables and values.
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Bitwise operators
5. Assignment operators
6. Special operators
➢ Identity operators
➢ Membership operators

BSC -VI Python_Programming (GUG) 25


# Examples of Arithmetic Operator

P R E P A R E D B Y : M R A

BSC -VI Python_Programming (GUG) 26


BSC -VI Python_Programming (GUG) 27
P R E P A R E D B Y : M R A

BSC -VI Python_Programming (GUG) 28


BSC -VI Python_Programming (GUG) 29
BSC -VI Python_Programming (GUG) 30
P R E P A R E D B Y : M R A

BSC -VI Python_Programming (GUG) 31


BSC -VI Python_Programming (GUG) 32
Ternary operator
Ternary operators also known as conditional expressions are operators that
evaluate something based on a condition being true or false. It was added to Python in
version 2.5. It simply allows to test a condition in a single line replacing the multiline if-
else making the code compact.

Ans: 10

BSC -VI Python_Programming (GUG) 33


PREPARED BY:MRA
is: 1 EXPRESSIONS IN PYTHON:

An expression is a combination of values, variables, and operators. An


expression is evaluated using assignment operator.

Examples:
>>> x=10 >>> x=10
>>> z=x+20 >>> y=20
>>> z >>> c=x+y
30 >>> c Result: 30

A value all by itself is a simple expression, and so is a variable.


>>> y=20
>>> y
20

Python also defines expressions only contain identifiers, literals, and


operators. So,
Identifiers: Any name that is used to define a class, function, variable module, or
object is an identifier.

Literals: These are language-independent terms in Python and should exist


independently in any programming language. In Python, there are the string literals,
byte literals, integer literals, floating point literals, and imaginary literals.

Operators: In Python you can implement the following operations using the
corresponding tokens.

BSC -VI Python_Programming (GUG) 34


PPARED BY:MRA

BSC -VI Python_Programming (GUG) 35


Some of the python expressions are:
Generator expression:
Type text here
Syntax: (compute(var) for var in iterable)

>>> x = (i for i in 'abc') #tuple comprehension


>>> x
<generator object <genexpr> at 0x033EEC30>
>>> print(x)
<generator object <genexpr> at 0x033EEC30>
You might expect this to print as ('a', 'b', 'c') but it prints as <generator object
<genexpr> at 0x02AAD710> The result of a tuple comprehension is not a tuple: it
is actually a generator. The only thing that you need to know now about a generator
now is that you can iterate over it, but ONLY ONCE.

Conditional expression:

Syntax: true_value if Condition else false_value

>>> x = "1" if True else "2"


>>> x
'1'

Type text here

BSC -VI Python_Programming (GUG) 36


P R E P A R E D B Y : M R A
DATA STRUCTURES
[str, list, tuple, dict, set]

String: -

In Python, Updation or deletion of characters from a String is not allowed.


This will cause an error because item assignment or item deletion from a String is
not supported. This is because Strings are immutable, hence elements of a String
cannot be changed once it has been assigned.
Strings in Python are identified as a contiguous set of characters represented
in the quotation marks. Python allows for either pairs of single or double quotes.
➢ 'hello' is the same as "hello".
➢ Strings can be output to screen using the print function.
For example: print("hello").
>>> print ("madhu raichur")
madhu raichur
>>> type ("madhu raichur")
<class 'str'>
>>> print (‘madhu raichur’)
madhu raichur
Suppressing Special Character:
Specifying a backslash (\) in front of the quote character in a string “escapes”
it and causes python to suppress its usual special meaning. It is then interpreted
simply as a literal single quote character:
>>> print("BSC FINAL YEAR 2023-24 (\') college")
BSC FINAL YEAR 2023-24 (\') college

>>> print(' BSC FINAL YEAR 2023-24 (\") college')


BSC FINAL YEAR 2023-24 (\") college

Type text here 37


BSC -VI Python_Programming (GUG)
The following is a table of escape sequences which cause Python to suppress the
usual special interpretation of a character in a string:
>>> print ('a\
.... b')
a....b
>>> print ('a\
b\
c')
abc
>>> print ('a \n b')
a
b
>>> print ("BSc VI \n college")
BSc VI
college

In Python (and almost all other common computer languages), a tab character
can be specified by the escape sequence \t:
>>> print("a\tb")
a b

BSC -VI Python_Programming (GUG) 38


List: -
➢ It is a general purpose most widely used in data structures
➢ List is a collection which is ordered and changeable and allows duplicate
members.
(Grow and shrink as needed, sequence type, sortable).
➢ To use a list, you must declare it first. Do this using square brackets and
separate values with commas.
➢ We can construct / create list in many ways.

Create a List:
list = ["aaa", "bbb", "ccc"]

Access Items
To access values in lists, use the square brackets for slicing along with the index or
indices to obtain value available at that index.

List Index
my_list = ['p','r','o','b','e']
print(my_list[0]) # Output: p
print(my_list[2]) # Output: o

Negative indexing
Python allows negative indexing for its sequences. The index of -1 refers to
the last item, -2 to the second last item and so on.
my_list = ['p','r','o','b','e']
print(my_list[-1]) # Output: e
print(my_list[-5]) # Output: p

BSC -VI Python_Programming (GUG) 39


P R E P A R E D B Y : M R A
How to slice lists in Python?

my_list = ['p','r','o','g','r','a','m','i','z']
print(my_list[2:5]) # elements 3rd to 5th
print(my_list[:-5]) # elements beginning to 4th
print(my_list[5:]) # elements 6th to end
print (my_list [:]) # elements beginning to end

List Manipulations
Methods that are available with list object in Python programming are:

BSC -VI Python_Programming (GUG) 40


index()
In simple terms, the index() method finds the given element in a list and
returns its position. If the same element is present more than once, the method returns the
index of the first occurrence of the element.
The syntax of the index() method is:
list.index(element)
Example
vowels = ['a', 'e', 'i', 'o', 'i', 'u'] # vowels list
index = vowels.index('e') # index of 'e'
print('The index of e:', index)
The index of e: 1
index = vowels.index('i') # index of the first 'i'
print('The index of i:', index)
The index of i: 2

append()
To add an item to the end of the list, use the append() method.
The syntax of the append() method is:
list.append(item)
Example
list = ["aaa", "bbb", "ccc"]
list.append("madhu")
print(list)
['aaa', 'bbb', 'ccc', 'madhu']

P R E P A R E D B Y : M R A 41
BSC -VI Python_Programming (GUG)
insert()
The insert() method inserts an element to the list at a given index.
The syntax of insert() method is
list.insert(index, element)
Example
fruits = ['aaa', 'bbb', 'ccc']
fruits.insert(1,"sree")
print(fruits)
['aaa', 'sree', 'bbb', 'ccc']
copy()
The copy() method returns a shallow copy of the list.
The syntax of copy() method is:
new_list = list.copy()
Example
fruits = ['aaa', 'bbb', 'ccc']
x=fruits.copy()
x
['aaa', 'bbb', 'ccc']
extend()
The extend() method adds the specified list elements (or any iterable) to the end of
the current list.
The syntax for extend() method
list.extend(seq)
Example
b1=['b','c','c++']
b2=['java','python','R']
b1.extend(b2)

BSC -VI Python_Programming (GUG) 42


print(b1)
['b', 'c', 'c++', 'java', 'python', 'R']
count()
Python list method count() returns count of how many times obj occurs in list.
The syntax for count() method
list.count(obj)
Example
List = [123, 'xyz', 'zara', 'abc', 123]
print ("Count for 123 : ", List.count(123) )
Count for 123 : 2
print ("Count for zara : ", List.count('zara') )
Count for zara : 1
remove()
The remove() method removes the first occurrence of the element with the specified
value.
Syntax
list.remove(elmnt)
Example
fruits = ['aaa', 'bbb', 'ccc']
fruits.remove('bbb')
fruits
['aaa', 'ccc']
pop()
The pop() method removes the element at the specified position.
Syntax
list.pop(pos)

BSC -VI Python_Programming (GUG) 43


Example
languages = ['Python', 'Java', 'C++', 'French', 'C']
return_value = languages.pop(3)
print('Return Value:', return_value)
Return Value: French
print('Updated List:', languages)
Updated List: ['Python', 'Java', 'C++', 'C']
reverse()
The reverse() method reverses the sorting order of the elements.
Syntax
list.reverse()
Example
OS = ['Windows', 'macOS', 'Linux']
print('Original List:', OS)
Original List: ['Windows', 'macOS', 'Linux']
OS.reverse()
print('Updated List:', OS)
Updated List: ['Linux', 'macOS', 'Windows']
sort()
The sort() method sorts the elements of a given list in a specific order - Ascending
or Descending.

The syntax of sort() method is:


list.sort(key=..., reverse=...)

Alternatively, you can also use Python's in-built function sorted() for the same purpose.
sorted(list, key=..., reverse=...)

P R E P A R E D B Y : M R A BSC -VI Python_Programming (GUG) 44


Example
vowels = ['e', 'a', 'u', 'o', 'i']
vowels.sort()
print('Sorted list:', vowels)
Sorted list: ['a', 'e', 'i', 'o', 'u']
len()
Python list function len() returns the number of elements in the list.
The syntax for len() method
len(list)
Example
list1, list2 = [123, 'xyz', 'zara'], [456, 'abc']
print( "First list length : ", len(list1))
First list length : 3
print ("Second list length : ", len(list2))
Second list length : 2
Nested List
A list can contain any sort object, even another list (sublist), which in turn can
contain sublists themselves, and so on. This is known as nested list. A nested list is
created by placing a comma-separated sequence of sublists.
Example1
L = ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', 'h']
print(L)

['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', 'h']

Example2
L = ['a', 'b', ['cc', 'dd', ['eee', 'fff']], 'g', 'h']

print(L[2])

BSC -VI Python_Programming (GUG) 45


['cc', 'dd', ['eee', 'fff']]

print(L[2][2])

['eee', 'fff']

print(L[2][2][0])

eee

Tuples:
A tuple is a collection which is ordered and unchangeable. In Python tuples
are written with round brackets.
• Supports all operations for sequences.
• Immutable, but member objects may be mutable.
• If the contents of a list shouldn’t change, use a tuple to prevent items from
accidently being added, changed, or deleted.
• Tuples are more efficient than list due to python’s implementation.
We can construct tuple in many ways:
X=() #no item tuple
X=(1,2,3)
X=tuple(list1)
X=1,2,3,4
Example:
>>> x=(1,2,3)
>>> print(x)
(1, 2, 3)
>>> x
(1, 2, 3)
-----------------------
>>> x=()
>>> x
()
----------------------------

BSC -VI Python_Programming (GUG) 46


PARED BY:MRA
>>> x=[4,5,66,9]
>>> y=tuple(x)
>>> y
(4, 5, 66, 9)
-----------------------------
>>> x=1,2,3,4
>>> x
(1, 2, 3, 4)
Some of the operations of tuple are:
• Access tuple items
• Change tuple items
• Loop through a tuple
• Count()
• Index()
• Length()

Access tuple items: Access tuple items by referring to the index number, inside square
brackets
>>> x=('a','b','c','g')
>>> print(x[2])
c
Change tuple items: Once a tuple is created, you cannot change its values. Tuples
are unchangeable.

P R E P A R E D B Y : M R A
BSC -VI Python_Programming (GUG) 47
Above error we can solve by doing typecasting method:

PREPARED BY:MRA

Loop through a tuple: We can loop the values of tuple using for loop
>>> x=(4,5,6,7,2,”madhu”)
>>> for i in x:
print(i)
4
5
6
7
2
Madhu
Count ():
Returns the number of times a specified value occurs in a tuple
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> x.count(2)
4
Index ():
Searches the tuple for a specified value and returns the position of where it was
found.
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)

BSC -VI Python_Programming (GUG) 48


>>> x.index(2)
1
(Or)
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=x.index(2)
>>> print(y)
1
Length ():
To know the number of items or values present in a tuple, we use len().
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=len(x)
>>> print(y)
12
Basic Tuples Operations
Tuples respond to the + and * operators much like strings; they mean
concatenation and repetition here too, except that the result is a new tuple.

BSC -VI Python_Programming (GUG) 49


Dictionaries:
A dictionary is a collection which is unordered, changeable and indexed. In
Python dictionaries are written with curly brackets, and they have keys and values.
• Key-value pairs
• Unordered
We can construct or create dictionary like:
X={1:’A’,2:’B’,3:’c’}
X=dict([(‘a’,3) (‘b’,4)]
X=dict(‘A’=1,’B’ =2)
Example:
dict1 = {"brand":"BSc VI","GFGCR":"college","year":2023}
dict1
{'brand': 'BSc VI', 'GFGCR': 'college', 'year': 2023}

Operations and methods:


Methods that are available with dictionary are tabulated below. Some of them
have already been used in the above examples.

BSC -VI Python_Programming (GUG) 50


P R E P A R E D B Y : M R A

Below are some dictionary operations:

1. To access specific value of a dictionary, we must pass its key,

>>> dict1 = {"brand":"BSc VI","GFGCR":"college","year":2023}


>>> x=dict1["brand"]
>>> x
'BSc VI'

BSC -VI Python_Programming (GUG) 51


2. To access keys and values and items of dictionary:
>>> dict1 = {"brand":"BSc VI","GFGCR":"college","year":2023}
>>> dict1.keys()
dict_keys(['brand', 'GFGCR', 'year'])

>>> dict1.values()
dict_values(['BSc VI', 'college', 2023])

>>> dict1.items()
dict_items([('brand', 'BSc VI'), ('GFGCR', 'college'), ('year', 2023)])

some more operations like:


➢ Add/change
➢ Remove
➢ Length
➢ Delete
Add/change values: You can change the value of a specific item by referring to its
key name
>>> dict1 = {"brand":"BSc VI","GFGCR":"college","year":2023}
>>> dict1["year"]=2024
>>> dict1
{'brand': 'BSc VI', 'GFGCR': 'college', 'year': 2024}

Remove(): It removes or pop the specific item of dictionary.


>>> dict1 = {"brand":"BSc VI","GFGCR":"college","year":2023}
>>> print(dict1.pop("GFGCR"))
college

BSC -VI Python_Programming (GUG) 52


>>> dict1
{'brand': 'BSc VI', 'year': 2024}

Delete: Deletes a particular item.


>>> x = {1:1, 2:4, 3:9, 4:16, 5:25}
>>> del x[5]
>>> x
{1: 1, 2: 4, 3: 9, 4: 16}

Length: we use len() method to get the length of dictionary.


>>>x={1: 1, 2: 4, 3: 9, 4: 16}
>>> y=len(x)
>>> y
4
Iterating over (key, value) pairs:
>>> x = {1:1, 2:4, 3:9, 4:16, 5:25}
>>> for key in x: for k,v in x.items():
print(key, x[key]) print(k,v)
11 11

24 24

39 39

4 16 4 16

5 25 5 25

BSC -VI Python_Programming (GUG) 53


P R E P A R E D B Y : M R A
Set:

BSC -VI Python_Programming (GUG) 54


P R E P A R E D B Y : M R A

BSC -VI Python_Programming (GUG) 55


BSC -VI Python_Programming (GUG) 56
NOTE:
Mutable and Immutable data types/objects:
➢ Example for mutable data types are: List, Set and Dictionary

➢ Example for Immutable data types are: Strings, tuple, int, float,
bool,Unicode.

***************** END OF UNIT – I *****************


P R E P A R E D B Y : M R A

BSC -VI Python_Programming (GUG) 57

You might also like