SlideShare a Scribd company logo
1 of 45
Python for Beginners(v3)
Dr.M.Rajendiran
Dept. of Computer Science and Engineering
Panimalar Engineering College
Install Python 3 On Ubuntu
Prerequisites
Step 1.A system running Ubuntu
Step 2.A user account with sudo privileges
Step 3.Access to a terminal command-line (Ctrl–Alt–T)
Step 4.Make sure your environment is configured to use
Python 3.8
2
Install Python 3
Now you can start the installation of Python 3.8.
$sudo apt install python3.8
Allow the process to complete and verify the Python
version was installed successfully
$python ––version
3
Installing and using Python on Windows is very simple.
Step 1: Download the Python Installer binaries
Step 2: Run the Executable Installer
Step 3: Add Python to environmental variables
Step 4: Verify the Python Installation
4
Python Installation
Open the Python website in your web browser.
https://www.python.org/downloads/windows/
Once the installer is downloaded, run the Python installer.
Add the following path
C:Program FilesPython37-32: for 64-bit installation
Once the installation is over, you will see a Python Setup
Successful window.
You are ready to start developing Python applications in
your Windows 10 system.
5
iPython Installation
If you already have Python installed, you can use pip to
install iPython using the following command:
$pip install iPython
To use it, type the following command in your computer’s
terminal:
$ipython
6
Compound Data Type
List
 List is an ordered sequence of items. Values in the list are called
elements.
 List of values separated by commas within square brackets[ ].
 Items in the lists can be of different data types.
Tuples
 A tuple is same as list.
 The set of elements is enclosed in parentheses.
 A tuple is an immutable list.
i.e. once a tuple has been created, you can't add elements to a
tuple or remove elements from the tuple.
 Tuple can be converted into list and list can be converted in to tuple.
Compound Data Type
Dictionary
 Dictionary is an unordered collection of elements.
 An element in dictionary has a key: value pair.
 All elements in dictionary are placed inside the curly braces{ }
 Elements in dictionaries are accessed via keys and not by their
position.
 The values of a dictionary can be any data type.
 Keys must be immutable data type.
List
1.List operations
2.List slices
3.List methods
4.List loop
5.Mutability
6.Aliasing
7.Cloning lists
8.List parameters
List
Operations on list
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Updating
6. Membership
7. Comparison
List
.
Operation Example Description
create a list
>>> a=[2,3,4,5,6,7,8,9,10]
>>> print(a)
[2, 3, 4, 5, 6, 7, 8, 9, 10]
we can create a list at compile
time
Indexing
>>> print(a[0])
2
>>> print(a[8])
10
>>> print(a[-1])
10
Accessing the item in the
position 0
Accessing the item in the
position 8
Accessing a last element using
negative indexing.
Slicing
>>> print(a[0:3])
[2, 3, 4]
>>> print(a[0:])
[2, 3, 4, 5, 6, 7, 8, 9, 10]
Printing a part of the list.
Concatenation
>>>b=[20,30]
>>> print(a+b)
[2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30]
Adding and printing the items of
two lists.
Repetition
>>> print(b*3)
[20, 30, 20, 30, 20, 30]
Create a multiple copies of the
same list.
Updating
>>> print(a[2])
4
>>> a[2]=100
>>> print(a)
[2, 3, 100, 5, 6, 7, 8, 9, 10]
Updating the list using index
value.
List
List slices
List slicing is an operation that extracts a subset of elements from an
list.
Operation Example Description
Membership
>>> a=[2,3,4,5,6,7,8,9,10]
>>> 5 in a
True
>>> 100 in a
False
>>> 2 not in a
False
Returns True if element is
present in list. Otherwise returns
false.
Comparison
>>> a=[2,3,4,5,6,7,8,9,10]
>>>b=[2,3,4]
>>> a==b
False
>>> a!=b
True
Returns True if all elements in
both elements are same.
Otherwise returns false
List
Syntax
listname[start:stop]
listname[start:stop:steps]
 Default start value is 0
 Default stop value is n-1
 [:] this will print the entire list
 [2:2] this will create a empty slice slices example
Slices Example Description
a[0:3]
>>> a=[9,8,7,6,5,4]
>>> a[0:3]
[9, 8, 7]
Printing a part of a list from 0 to
2.
a[:4] >>> a[:4]
[9, 8, 7, 6]
Default start value is 0. so prints
from 0 to 3
a[1:] >>> a[1:]
[8, 7, 6, 5, 4]
Default stop value will be n-1. so
prints from 1 to 5
List
List methods
 Methods used in lists are used to manipulate the data quickly.
 These methods work only on lists.
 They do not work on the other sequence types that are not mutable,
that is, the values cannot be changed.
Syntax
list name.method name( element/index/list)
Slices Example Description
list.append(element)
>>> a=[1,2,3,4,5]
>>> a.append(6)
>>> print(a)
[1, 2, 3, 4, 5, 6]
Add an element to the end of the
list
list.insert(index,element
)
>>> a.insert(0,0)
>>> print(a)
[0, 1, 2, 3, 4, 5, 6]
Insert an item at the defined
index
min(list) >>> min(a)
2
Return the minimum element in a
list
List
. Syntax Example Description
list.extend(b)
>>> b=[7,8,9]
>>> a.extend(b)
>>> print(a)
[0, 1, 2, 3, 4, 5, 6, 7, 8,9]
Add all elements of a list to the
another list
list,index(element)
>>> a.index(8)
8
Returns the index of the element
list.sort()
>>> a.sort()
>>> print(a)
[0, 1, 2, 3, 4, 5, 6, 7, 8,9]
Sort items in a list
list.reverse()
>>> a.reverse()
>>> print(a)
[9,8, 7, 6, 5, 4, 3, 2, 1, 0]
Reverse the order.
list.remove(element)
>>> a.remove(0)
>>> print(a)
[9,8,7, 6, 5, 4, 3, 2,1]
Removes an item from the list
list.copy()
>>> b=a.copy()
>>> print(b)
[9,8,7, 6, 5, 4, 3, 2,1]
Copy from a to b
len(list)
>>>len(a)
9
Length of the list
List
Try yourself:
list.pop()
list.pop(index)
list.remove(element)
list.count(element)
max(list)
list.clear()
del(list)
List
List loops
1. for loop
2. while loop
3. infinite loop
for Loop
 The for loop in python is used to iterate over a sequence (list, tuple,
string) or other iterable objects.
 Iterating over a sequence is called traversal.
 Loop continues until we reach the last item in the sequence.
 The body of for loop is separated from the rest of the code using
indentation.
Syntax:
for variable in sequence:
List
Example
Accessing element
a=[10,20,30,40,50]
for i in a:
print(i)
Output
10
20
30
40
50
Accessing index output
a=[10,20,30,40,50]
for i in range(0,len(a),1):
print(i)
output
0
1
2
3
4
Accessing element using range
a=[10,20,30,40,50]
for i in range(0,len(a),1):
print(a[i])
----------------------------------------------------------
print(id(a[i])) # for memory address
output
10
20
30
40
50
List
While loop
 The while loop is used to iterate over a block of code as long as the
test condition is true.
 When the condition is tested and the result is false, the loop body
will be skipped and the first statement after the while loop will be
executed.
Syntax:
while (condition):
body of the statement
Example: Sum of the elements in
list
a=[1,2,3,4,5]
i=0
sum=0
while i<len(a):
sum=sum+a[i]
i=i+1
print(sum)
Output
15
List
infinite Loop
 A loop becomes infinite loop if the condition becomes false.
 It keeps on running. Such loops are called infinite loop.
Example:
a=1
while (a==1):
n=int(input("enter the number"))
print("you entered:" , n)
Output
Enter the number 10
you entered:10
Enter the number 12
you entered:12
Enter the number 16
you entered:16
List
Mutability
 Lists are mutable.(It can be changed)
 Mutability is the ability for certain types of data to be changed without
entirely recreating it.
 An item can be changed in a list by accessing it directly as part of the
assignment statement.
 Using the indexing operator on the left side of an assignment, one of
the list items can be updated.
 Example:
>>> a=[1,2,3,4,5]
>>> a[0]=100
>>> print(a)
[100, 2, 3, 4, 5]
changing single element
>>> a=[1,2,3,4,5]
>>> a[0:3]=[100,100,100]
>>> print(a)
[100, 100, 100, 4, 5]
changing multiple element
List
Aliasing(copying)
 Creating a copy of a list is called aliasing.
 When you create a copy both list will be having same memory location.
 Changes in one list will affect another list.
 Aliasing refers to having different names for same list values.
Example:
a= [1, 2, 3 ,4 ,5]
b=a
print (b)
a is b
a[0]=100
print(a)
print(b)
[1, 2, 3, 4, 5]
[100,2,3,4,5]
[100,2,3,4,5]
List
Cloning
 Creating a copy of a same list of elements with different memory
locations is called cloning.
 Changes in one list will not affect locations of another list.
 Cloning is a process of making a copy of the list without modifying the
original list.
1. Slicing
2. list()method
3. copy() method
Example:
cloning using Slicing
>>>a=[1,2,3,4,5]
>>>b=a[:]
>>>print(b)
[1,2,3,4,5]
>>>a is b
False
List
. clonning using list() method
>>>a=[1,2,3,4,5]
>>>b=list(a)
>>>print(b)
[1,2,3,4,5]
>>>a is b
false
>>>a[0]=100
>>>print(a)
>>>a=[100,2,3,4,5]
>>>print(b)
>>>b=[1,2,3,4,5]
clonning using copy() method
a=[1,2,3,4,5]
>>>b=a.copy()
>>> print(b)
[1, 2, 3, 4, 5]
>>> a is b
False
List
List as parameters
 Arguments are passed by reference.
 If any changes are done in the parameter, then the changes also
reflects back in the calling function.
 When a list to a function is passed, the function gets a reference to the
list.
 Passing a list as an argument actually passes a reference to the list, not
a copy of the list.
 Lists are mutable, changes made to the elements.
 Example
def remove(a):
a.remove(1)
a=[1,2,3,4,5]
remove(a)
print(a)
Output
[2,3,4,5]
List
. Example 2:
def inside(a):
for i in range(0,len(a),1):
a[i]=a[i]+10
print(“inner”,a)
a=[1,2,3,4,5]
inside(a)
print(“outer”,a)
output
inner [11, 12, 13, 14, 15]
outer [11, 12, 13, 14, 15]
Example3:
def insert(a):
a.insert(0,30)
a=[1,2,3,4,5]
insert(a)
print(a)
output
[30, 1, 2, 3, 4, 5]
List
Practice
1.list=[‘p’,’r’,’I’,’n’,’t’]
print list[-3:]
Ans:
Error, no parenthesis in print statement.
2.Listout built-in functions.
Ans:
max(3,4),min(3,4),len(“raj”),range(2,8,1),round(7.8),float(5),int(5.0)
3.List is mutable-Justify
Ans:
List is an ordered sequence of items. Values in the list are called elements/items.
List is mutable. i.e. Values can be changed.
a=[1,2,3,4,5,6,7,8,9,10]
a[2]=100
print(a) -> [1,2,100,4,5,6,7,8,9,10]
Advanced list processing
List Comprehension
 List comprehensions provide a brief way to apply operations on a list.
 It creates a new list in which each element is the result of applying a
given operation in a list.
 It consists of brackets containing an expression followed by a “for”
clause, then a list.
 The list comprehension always returns a result list.
Syntax
list=[ expression for item in list if conditional ]
Advanced list processing
.
List Comprehension output
>>>L=[x**2 for x in range(0,5)]
>>>print(L)
[0, 1, 4, 9, 16]
>>>[x for x in range(1,10) if x%2==0] [2, 4, 6, 8]
>>>[x for x in 'Python Programming' if x in
['a','e','i','o','u']]
['o', 'o', 'a', 'i']
>>>mixed=[1,2,"a",3,4.2]
>>> [x**2 for x in mixed if type(x)==int]
[1, 4, 9]
>>>[x+3 for x in [1,2,3]] [4, 5, 6]
>>> [x*x for x in range(5)] [0, 1, 4, 9, 16]
>>> num=[-1,2,-3,4,-5,6,-7]
>>> [x for x in num if x>=0]
[2, 4, 6]
>>> str=["this","is","an","example"]
>>> element=[word[0] for word in str]
>>> print(element)
['t', 'i', 'a', 'e']
Nested list
 List inside another list is called nested list.
Example
>>> a=[56,34,5,[34,57]]
>>> a[0]
56
>>> a[3]
[34, 57]
>>> a[3][0]
34
>>> a[3][1]
57
Tuple
 A tuple is same as list, except in parentheses instead of square
brackets.
 A tuple is an immutable list. i.e. can not be changed.
 Tuple can be converted into list and list can be converted in to tuple.
Benefit:
 Tuples are faster than lists.
 Tuple can be protected the data.
 Tuples can be used as keys in dictionaries, while lists can't.
Operations on Tuples:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Membership
6. Comparison
Tuple
 . Operations Example Description
Creating a tuple
>>>a=(20,40,60,”raj”,”man”) Creating the tuple with different
data types.
Indexing
>>>print(a[0])
20
Accessing the item in the position
0
Slicing
>>>print(a[1:3])
(40,60)
Displaying elements from 1st to
2nd.
Concatenation
>>> b=(2,4)
>>>print(a+b)
>>>(20,40,60,”raj”,”man”,2,4)
Adding tuple elements.
Repetition
>>>print(b*2)
>>>(2,4,2,4)
Repeating the tuple
Membership
>>> a=(2,3,4,5,6,7,8,9,10)
>>> 5 in a
True
>>> 2 not in a
False
If element is present in tuple
returns TRUE else FALSE
Comparison
>>> a=(2,3,4,5,6,7,8,9,10)
>>>b=(2,3,4)
>>> a==b
False
If all elements in both tuple same
display TRUE else FALSE
Tuple
Tuple methods
 Tuple is immutable. i.e. changes cannot be done on the elements of a
tuple once it is assigned.
Methods Example Description
tuple.index(element)
>>> a=(1,2,3,4,5)
>>> a.index(5)
4
Display the index number of
element.
tuple.count(element)
>>>a=(1,2,3,4,5)
>>> a.count(3)
1
Number of count of the given
element.
len(tuple)
>>> len(a)
5
The length of the tuple
min(tuple)
>>> min(a)
1
The minimum element in a tuple
max(tuple)
>>>max(a)
5
The maximum element in a tuple
del(tuple) >>>del(a) Delete the tuple.
Tuple
Convert tuple into list
Convert list into tuple
Methods
Example
Description
list(tuple)
>>>a=(1,2,3,4,5)
>>>a=list(a)
>>>print(a)
[1, 2, 3, 4, 5]
Convert the given tuple into
list.
Methods
Example
Description
tuple(list)
>>> a=[1,2,3,4,5]
>>> a=tuple(a)
>>> print(a)
(1, 2, 3, 4, 5)
Convert the given list into
tuple.
Tuple
Tuple Assignment
 Tuple assignment allows, variables on the left of an assignment operator and
values on the right of the assignment operator.
 Multiple assignment works by creating a tuple of expressions from the right
hand side, and a tuple of targets from the left, and then matching each
expression to a target.
 It is useful to swap the values of two variables.
Example:
Swapping using temporary variable Swapping using tuple assignment
a=20
b=50
temp=a
a=b
b=temp
print("value after swapping is",a,b)
a=20
b=50
(a,b)=(b,a)
print("value after swapping is",a,b)
Tuple
Multiple assignments
 Multiple values can be assigned to multiple variables using tuple
assignment.
Example
>>>(a,b,c)=(1,2,3)
>>>print(a)
1
>>>print(b)
2
>>>print(c)
3
Tuple
Tuple as return value
 A Tuple is a comma separated sequence of items.
 It is created with or without ( ).
 A function can return one value.
 if you want to return more than one value from a function then use tuple
as return value.
Example:
Program to find quotient and reminder output
def div(a,b):
r=a%b
q=a//b
return(r,q)
a=eval(input("enter a value:"))
b=eval(input("enter b value:"))
r,q=div(a,b)
print("reminder:",r)
print("quotient:",q)
enter a value:5
enter b value:4
reminder: 1
quotient: 1
Tuple
Tuple as argument
 The parameter name that begins with * gathers argument into a tuple.
Example
def printall(*args):
print(args)
printall(2,3,'a')
Output:
(2, 3, 'a')
Dictionaries
 Dictionary is an unordered collection of elements.
 An element in dictionary has a key:value pair.
 All elements in dictionary are placed inside the curly braces i.e. { }
 Elements in Dictionaries are accessed via keys.
 The values of a dictionary can be any data type.
 Keys must be immutable data type.
Operations on dictionary
1. Accessing an element
2. Update
3. Add element
4. Membership
Dictionaries
 . Operations Example Description
Creating a
dictionary
>>> a={1:"one",2:"two"}
>>> print(a)
{1: 'one', 2: 'two'}
Creating the dictionary with
different data types.
Accessing an
element
>>> a[1]
'one'
>>> a[0]
KeyError: 0
Accessing the elements by
using keys.
Update
>>> a[1]="ONE"
>>> print(a)
{1: 'ONE', 2: 'two'}
Assigning a new value to key.
Add element
>>> a[3]="three"
>>> print(a)
{1: 'ONE', 2: 'two', 3: 'three'}
Add new element in to the
dictionary with key.
Membership
a={1: 'ONE', 2: 'two', 3: 'three'}
>>> 1 in a
True
>>> 3 not in a
False
If the key is present in
dictionary returns TRUE else
FALSE
Dictionaries
Methods in dictionary
Method Example Description
Dictionary.copy()
a={1: 'ONE', 2: 'two', 3: 'three'}
>>> b=a.copy()
>>> print(b)
{1: 'ONE', 2: 'two', 3: 'three'}
copy dictionary ’a’ to
dictionary ‘b’
Dictionary.items()
>>> a.items()
dict_items([(1, 'ONE'), (2,
'two'), (3, 'three')])
It displays a list of
dictionary’s (key, value) tuple
pairs.
Dictionary.key() >>> a.keys()
dict_keys([1, 2, 3])
Displays list of keys in a
dictionary.
Dictionary.values()
>>> a.values()
dict_values(['ONE', 'two',
'three'])
Displays list of values in a
dictionary.
Dictionary.pop(key
)
>>> a.pop(3)
'three'
>>> print(a)
{1: 'ONE', 2: 'two'}
Remove the element with
key.
Dictionaries
Try yourself
Dictionary.setdefault(key,value)
Dictionary.update(dictionary)
Dictionary.fromkeys(key,value)
len(Dictionary name)
Dictionary.clear()
del(Dictionary name)
Comparison of List, Tuples and Dictionary
. List Tuple Dictionary
A list is mutable A tuple is immutable A dictionary is mutable
Lists are dynamic Tuples are static Values can be of any
data type and can
repeat.
Keys must be of
immutable type
Homogenous Heterogeneous Homogenous
Slicing can be done Slicing can be done Slicing can't be done
Assignment
1.Addition of matrix
2.Multiplication of matrix
3.Transpose of matrix
4.Selection sort
5.Insertion sort
6.Merge sort
7.Histogram
email:mrajen@rediffmail.com
.

More Related Content

What's hot

A presentation on prim's and kruskal's algorithm
A presentation on prim's and kruskal's algorithmA presentation on prim's and kruskal's algorithm
A presentation on prim's and kruskal's algorithmGaurav Kolekar
 
Hashing And Hashing Tables
Hashing And Hashing TablesHashing And Hashing Tables
Hashing And Hashing TablesChinmaya M. N
 
Python SQite3 database Tutorial | SQlite Database
Python SQite3 database Tutorial | SQlite DatabasePython SQite3 database Tutorial | SQlite Database
Python SQite3 database Tutorial | SQlite DatabaseElangovanTechNotesET
 
Searching Techniques and Analysis
Searching Techniques and AnalysisSearching Techniques and Analysis
Searching Techniques and AnalysisAkashBorse2
 
Polynomial reppresentation using Linkedlist-Application of LL.pptx
Polynomial reppresentation using Linkedlist-Application of LL.pptxPolynomial reppresentation using Linkedlist-Application of LL.pptx
Polynomial reppresentation using Linkedlist-Application of LL.pptxAlbin562191
 
16. Concurrency Control in DBMS
16. Concurrency Control in DBMS16. Concurrency Control in DBMS
16. Concurrency Control in DBMSkoolkampus
 
Avl trees
Avl treesAvl trees
Avl treesppreeta
 
INTER PROCESS COMMUNICATION (IPC).pptx
INTER PROCESS COMMUNICATION (IPC).pptxINTER PROCESS COMMUNICATION (IPC).pptx
INTER PROCESS COMMUNICATION (IPC).pptxLECO9
 
Lec 17 heap data structure
Lec 17 heap data structureLec 17 heap data structure
Lec 17 heap data structureSajid Marwat
 
Binary Search Tree in Data Structure
Binary Search Tree in Data StructureBinary Search Tree in Data Structure
Binary Search Tree in Data StructureDharita Chokshi
 
Data Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search TreeData Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search TreeManishPrajapati78
 

What's hot (20)

A presentation on prim's and kruskal's algorithm
A presentation on prim's and kruskal's algorithmA presentation on prim's and kruskal's algorithm
A presentation on prim's and kruskal's algorithm
 
Hashing And Hashing Tables
Hashing And Hashing TablesHashing And Hashing Tables
Hashing And Hashing Tables
 
Python SQite3 database Tutorial | SQlite Database
Python SQite3 database Tutorial | SQlite DatabasePython SQite3 database Tutorial | SQlite Database
Python SQite3 database Tutorial | SQlite Database
 
Timestamp protocols
Timestamp protocolsTimestamp protocols
Timestamp protocols
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Searching Techniques and Analysis
Searching Techniques and AnalysisSearching Techniques and Analysis
Searching Techniques and Analysis
 
6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx
 
Polynomial reppresentation using Linkedlist-Application of LL.pptx
Polynomial reppresentation using Linkedlist-Application of LL.pptxPolynomial reppresentation using Linkedlist-Application of LL.pptx
Polynomial reppresentation using Linkedlist-Application of LL.pptx
 
Time and Space Complexity
Time and Space ComplexityTime and Space Complexity
Time and Space Complexity
 
Python - object oriented
Python - object orientedPython - object oriented
Python - object oriented
 
16. Concurrency Control in DBMS
16. Concurrency Control in DBMS16. Concurrency Control in DBMS
16. Concurrency Control in DBMS
 
Avl trees
Avl treesAvl trees
Avl trees
 
INTER PROCESS COMMUNICATION (IPC).pptx
INTER PROCESS COMMUNICATION (IPC).pptxINTER PROCESS COMMUNICATION (IPC).pptx
INTER PROCESS COMMUNICATION (IPC).pptx
 
TCP/IP Basics
TCP/IP BasicsTCP/IP Basics
TCP/IP Basics
 
Lec 17 heap data structure
Lec 17 heap data structureLec 17 heap data structure
Lec 17 heap data structure
 
linked list
linked list linked list
linked list
 
Binary Search Tree in Data Structure
Binary Search Tree in Data StructureBinary Search Tree in Data Structure
Binary Search Tree in Data Structure
 
Data Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search TreeData Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search Tree
 
Pthread
PthreadPthread
Pthread
 
Python recursion
Python recursionPython recursion
Python recursion
 

Similar to Python for Beginners(v3)

Python Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, ExceptionsPython Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, ExceptionsSreedhar Chowdam
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxMihirDatir
 
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdfGE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdfAsst.prof M.Gokilavani
 
Python List.ppt
Python List.pptPython List.ppt
Python List.pptT PRIYA
 
List_tuple_dictionary.pptx
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
List_tuple_dictionary.pptxChandanVatsa2
 
Python elements list you can study .pdf
Python elements list you can study  .pdfPython elements list you can study  .pdf
Python elements list you can study .pdfAUNGHTET61
 
‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptxRamiHarrathi1
 
python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdfAshaWankar1
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdfNehaSpillai1
 
Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdfNehaSpillai1
 
The Ring programming language version 1.10 book - Part 30 of 212
The Ring programming language version 1.10 book - Part 30 of 212The Ring programming language version 1.10 book - Part 30 of 212
The Ring programming language version 1.10 book - Part 30 of 212Mahmoud Samir Fayed
 
The Ring programming language version 1.5.3 book - Part 22 of 184
The Ring programming language version 1.5.3 book - Part 22 of 184The Ring programming language version 1.5.3 book - Part 22 of 184
The Ring programming language version 1.5.3 book - Part 22 of 184Mahmoud Samir Fayed
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks QueuesIntro C# Book
 

Similar to Python for Beginners(v3) (20)

Unit - 4.ppt
Unit - 4.pptUnit - 4.ppt
Unit - 4.ppt
 
Python Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, ExceptionsPython Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, Exceptions
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptx
 
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdfGE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
 
Python List.ppt
Python List.pptPython List.ppt
Python List.ppt
 
Chapter 15 Lists
Chapter 15 ListsChapter 15 Lists
Chapter 15 Lists
 
Slicing in Python - What is It?
Slicing in Python - What is It?Slicing in Python - What is It?
Slicing in Python - What is It?
 
Module III.pdf
Module III.pdfModule III.pdf
Module III.pdf
 
Python lists
Python listsPython lists
Python lists
 
List_tuple_dictionary.pptx
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
List_tuple_dictionary.pptx
 
Python elements list you can study .pdf
Python elements list you can study  .pdfPython elements list you can study  .pdf
Python elements list you can study .pdf
 
‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx
 
python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdf
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdf
 
Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdf
 
The Ring programming language version 1.10 book - Part 30 of 212
The Ring programming language version 1.10 book - Part 30 of 212The Ring programming language version 1.10 book - Part 30 of 212
The Ring programming language version 1.10 book - Part 30 of 212
 
Python lists &amp; sets
Python lists &amp; setsPython lists &amp; sets
Python lists &amp; sets
 
Module-2.pptx
Module-2.pptxModule-2.pptx
Module-2.pptx
 
The Ring programming language version 1.5.3 book - Part 22 of 184
The Ring programming language version 1.5.3 book - Part 22 of 184The Ring programming language version 1.5.3 book - Part 22 of 184
The Ring programming language version 1.5.3 book - Part 22 of 184
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
 

More from Panimalar Engineering College (8)

Python for Data Science
Python for Data SciencePython for Data Science
Python for Data Science
 
Python for Beginners(v2)
Python for Beginners(v2)Python for Beginners(v2)
Python for Beginners(v2)
 
Python for Beginners(v1)
Python for Beginners(v1)Python for Beginners(v1)
Python for Beginners(v1)
 
Introduction to Machine Learning
Introduction to Machine LearningIntroduction to Machine Learning
Introduction to Machine Learning
 
Cellular Networks
Cellular NetworksCellular Networks
Cellular Networks
 
Wireless Networks
Wireless NetworksWireless Networks
Wireless Networks
 
Wireless Networks
Wireless NetworksWireless Networks
Wireless Networks
 
Multiplexing,LAN Cabling,Routers,Core and Distribution Networks
Multiplexing,LAN Cabling,Routers,Core and Distribution NetworksMultiplexing,LAN Cabling,Routers,Core and Distribution Networks
Multiplexing,LAN Cabling,Routers,Core and Distribution Networks
 

Recently uploaded

BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...Nguyen Thanh Tu Collection
 
Graduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptxGraduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptxneillewis46
 
demyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptxdemyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptxMohamed Rizk Khodair
 
Observing-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxObserving-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxAdelaideRefugio
 
Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...EduSkills OECD
 
Scopus Indexed Journals 2024 - ISCOPUS Publications
Scopus Indexed Journals 2024 - ISCOPUS PublicationsScopus Indexed Journals 2024 - ISCOPUS Publications
Scopus Indexed Journals 2024 - ISCOPUS PublicationsISCOPE Publication
 
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...Gary Wood
 
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSean M. Fox
 
male presentation...pdf.................
male presentation...pdf.................male presentation...pdf.................
male presentation...pdf.................MirzaAbrarBaig5
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...Nguyen Thanh Tu Collection
 
ANTI PARKISON DRUGS.pptx
ANTI         PARKISON          DRUGS.pptxANTI         PARKISON          DRUGS.pptx
ANTI PARKISON DRUGS.pptxPoojaSen20
 
Major project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesMajor project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesAmanpreetKaur157993
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...EADTU
 
An overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismAn overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismDabee Kamal
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppCeline George
 
The Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFThe Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFVivekanand Anglo Vedic Academy
 

Recently uploaded (20)

BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
 
Graduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptxGraduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptx
 
Including Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdfIncluding Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdf
 
demyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptxdemyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptx
 
Observing-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxObserving-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptx
 
Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...
 
Scopus Indexed Journals 2024 - ISCOPUS Publications
Scopus Indexed Journals 2024 - ISCOPUS PublicationsScopus Indexed Journals 2024 - ISCOPUS Publications
Scopus Indexed Journals 2024 - ISCOPUS Publications
 
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
 
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
 
male presentation...pdf.................
male presentation...pdf.................male presentation...pdf.................
male presentation...pdf.................
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
 
ANTI PARKISON DRUGS.pptx
ANTI         PARKISON          DRUGS.pptxANTI         PARKISON          DRUGS.pptx
ANTI PARKISON DRUGS.pptx
 
Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"
 
Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"
 
Major project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesMajor project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategies
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
 
An overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismAn overview of the various scriptures in Hinduism
An overview of the various scriptures in Hinduism
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio App
 
The Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFThe Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDF
 

Python for Beginners(v3)

  • 1. Python for Beginners(v3) Dr.M.Rajendiran Dept. of Computer Science and Engineering Panimalar Engineering College
  • 2. Install Python 3 On Ubuntu Prerequisites Step 1.A system running Ubuntu Step 2.A user account with sudo privileges Step 3.Access to a terminal command-line (Ctrl–Alt–T) Step 4.Make sure your environment is configured to use Python 3.8 2
  • 3. Install Python 3 Now you can start the installation of Python 3.8. $sudo apt install python3.8 Allow the process to complete and verify the Python version was installed successfully $python ––version 3
  • 4. Installing and using Python on Windows is very simple. Step 1: Download the Python Installer binaries Step 2: Run the Executable Installer Step 3: Add Python to environmental variables Step 4: Verify the Python Installation 4
  • 5. Python Installation Open the Python website in your web browser. https://www.python.org/downloads/windows/ Once the installer is downloaded, run the Python installer. Add the following path C:Program FilesPython37-32: for 64-bit installation Once the installation is over, you will see a Python Setup Successful window. You are ready to start developing Python applications in your Windows 10 system. 5
  • 6. iPython Installation If you already have Python installed, you can use pip to install iPython using the following command: $pip install iPython To use it, type the following command in your computer’s terminal: $ipython 6
  • 7. Compound Data Type List  List is an ordered sequence of items. Values in the list are called elements.  List of values separated by commas within square brackets[ ].  Items in the lists can be of different data types. Tuples  A tuple is same as list.  The set of elements is enclosed in parentheses.  A tuple is an immutable list. i.e. once a tuple has been created, you can't add elements to a tuple or remove elements from the tuple.  Tuple can be converted into list and list can be converted in to tuple.
  • 8. Compound Data Type Dictionary  Dictionary is an unordered collection of elements.  An element in dictionary has a key: value pair.  All elements in dictionary are placed inside the curly braces{ }  Elements in dictionaries are accessed via keys and not by their position.  The values of a dictionary can be any data type.  Keys must be immutable data type.
  • 9. List 1.List operations 2.List slices 3.List methods 4.List loop 5.Mutability 6.Aliasing 7.Cloning lists 8.List parameters
  • 10. List Operations on list 1. Indexing 2. Slicing 3. Concatenation 4. Repetitions 5. Updating 6. Membership 7. Comparison
  • 11. List . Operation Example Description create a list >>> a=[2,3,4,5,6,7,8,9,10] >>> print(a) [2, 3, 4, 5, 6, 7, 8, 9, 10] we can create a list at compile time Indexing >>> print(a[0]) 2 >>> print(a[8]) 10 >>> print(a[-1]) 10 Accessing the item in the position 0 Accessing the item in the position 8 Accessing a last element using negative indexing. Slicing >>> print(a[0:3]) [2, 3, 4] >>> print(a[0:]) [2, 3, 4, 5, 6, 7, 8, 9, 10] Printing a part of the list. Concatenation >>>b=[20,30] >>> print(a+b) [2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30] Adding and printing the items of two lists. Repetition >>> print(b*3) [20, 30, 20, 30, 20, 30] Create a multiple copies of the same list. Updating >>> print(a[2]) 4 >>> a[2]=100 >>> print(a) [2, 3, 100, 5, 6, 7, 8, 9, 10] Updating the list using index value.
  • 12. List List slices List slicing is an operation that extracts a subset of elements from an list. Operation Example Description Membership >>> a=[2,3,4,5,6,7,8,9,10] >>> 5 in a True >>> 100 in a False >>> 2 not in a False Returns True if element is present in list. Otherwise returns false. Comparison >>> a=[2,3,4,5,6,7,8,9,10] >>>b=[2,3,4] >>> a==b False >>> a!=b True Returns True if all elements in both elements are same. Otherwise returns false
  • 13. List Syntax listname[start:stop] listname[start:stop:steps]  Default start value is 0  Default stop value is n-1  [:] this will print the entire list  [2:2] this will create a empty slice slices example Slices Example Description a[0:3] >>> a=[9,8,7,6,5,4] >>> a[0:3] [9, 8, 7] Printing a part of a list from 0 to 2. a[:4] >>> a[:4] [9, 8, 7, 6] Default start value is 0. so prints from 0 to 3 a[1:] >>> a[1:] [8, 7, 6, 5, 4] Default stop value will be n-1. so prints from 1 to 5
  • 14. List List methods  Methods used in lists are used to manipulate the data quickly.  These methods work only on lists.  They do not work on the other sequence types that are not mutable, that is, the values cannot be changed. Syntax list name.method name( element/index/list) Slices Example Description list.append(element) >>> a=[1,2,3,4,5] >>> a.append(6) >>> print(a) [1, 2, 3, 4, 5, 6] Add an element to the end of the list list.insert(index,element ) >>> a.insert(0,0) >>> print(a) [0, 1, 2, 3, 4, 5, 6] Insert an item at the defined index min(list) >>> min(a) 2 Return the minimum element in a list
  • 15. List . Syntax Example Description list.extend(b) >>> b=[7,8,9] >>> a.extend(b) >>> print(a) [0, 1, 2, 3, 4, 5, 6, 7, 8,9] Add all elements of a list to the another list list,index(element) >>> a.index(8) 8 Returns the index of the element list.sort() >>> a.sort() >>> print(a) [0, 1, 2, 3, 4, 5, 6, 7, 8,9] Sort items in a list list.reverse() >>> a.reverse() >>> print(a) [9,8, 7, 6, 5, 4, 3, 2, 1, 0] Reverse the order. list.remove(element) >>> a.remove(0) >>> print(a) [9,8,7, 6, 5, 4, 3, 2,1] Removes an item from the list list.copy() >>> b=a.copy() >>> print(b) [9,8,7, 6, 5, 4, 3, 2,1] Copy from a to b len(list) >>>len(a) 9 Length of the list
  • 17. List List loops 1. for loop 2. while loop 3. infinite loop for Loop  The for loop in python is used to iterate over a sequence (list, tuple, string) or other iterable objects.  Iterating over a sequence is called traversal.  Loop continues until we reach the last item in the sequence.  The body of for loop is separated from the rest of the code using indentation. Syntax: for variable in sequence:
  • 18. List Example Accessing element a=[10,20,30,40,50] for i in a: print(i) Output 10 20 30 40 50 Accessing index output a=[10,20,30,40,50] for i in range(0,len(a),1): print(i) output 0 1 2 3 4 Accessing element using range a=[10,20,30,40,50] for i in range(0,len(a),1): print(a[i]) ---------------------------------------------------------- print(id(a[i])) # for memory address output 10 20 30 40 50
  • 19. List While loop  The while loop is used to iterate over a block of code as long as the test condition is true.  When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed. Syntax: while (condition): body of the statement Example: Sum of the elements in list a=[1,2,3,4,5] i=0 sum=0 while i<len(a): sum=sum+a[i] i=i+1 print(sum) Output 15
  • 20. List infinite Loop  A loop becomes infinite loop if the condition becomes false.  It keeps on running. Such loops are called infinite loop. Example: a=1 while (a==1): n=int(input("enter the number")) print("you entered:" , n) Output Enter the number 10 you entered:10 Enter the number 12 you entered:12 Enter the number 16 you entered:16
  • 21. List Mutability  Lists are mutable.(It can be changed)  Mutability is the ability for certain types of data to be changed without entirely recreating it.  An item can be changed in a list by accessing it directly as part of the assignment statement.  Using the indexing operator on the left side of an assignment, one of the list items can be updated.  Example: >>> a=[1,2,3,4,5] >>> a[0]=100 >>> print(a) [100, 2, 3, 4, 5] changing single element >>> a=[1,2,3,4,5] >>> a[0:3]=[100,100,100] >>> print(a) [100, 100, 100, 4, 5] changing multiple element
  • 22. List Aliasing(copying)  Creating a copy of a list is called aliasing.  When you create a copy both list will be having same memory location.  Changes in one list will affect another list.  Aliasing refers to having different names for same list values. Example: a= [1, 2, 3 ,4 ,5] b=a print (b) a is b a[0]=100 print(a) print(b) [1, 2, 3, 4, 5] [100,2,3,4,5] [100,2,3,4,5]
  • 23. List Cloning  Creating a copy of a same list of elements with different memory locations is called cloning.  Changes in one list will not affect locations of another list.  Cloning is a process of making a copy of the list without modifying the original list. 1. Slicing 2. list()method 3. copy() method Example: cloning using Slicing >>>a=[1,2,3,4,5] >>>b=a[:] >>>print(b) [1,2,3,4,5] >>>a is b False
  • 24. List . clonning using list() method >>>a=[1,2,3,4,5] >>>b=list(a) >>>print(b) [1,2,3,4,5] >>>a is b false >>>a[0]=100 >>>print(a) >>>a=[100,2,3,4,5] >>>print(b) >>>b=[1,2,3,4,5] clonning using copy() method a=[1,2,3,4,5] >>>b=a.copy() >>> print(b) [1, 2, 3, 4, 5] >>> a is b False
  • 25. List List as parameters  Arguments are passed by reference.  If any changes are done in the parameter, then the changes also reflects back in the calling function.  When a list to a function is passed, the function gets a reference to the list.  Passing a list as an argument actually passes a reference to the list, not a copy of the list.  Lists are mutable, changes made to the elements.  Example def remove(a): a.remove(1) a=[1,2,3,4,5] remove(a) print(a) Output [2,3,4,5]
  • 26. List . Example 2: def inside(a): for i in range(0,len(a),1): a[i]=a[i]+10 print(“inner”,a) a=[1,2,3,4,5] inside(a) print(“outer”,a) output inner [11, 12, 13, 14, 15] outer [11, 12, 13, 14, 15] Example3: def insert(a): a.insert(0,30) a=[1,2,3,4,5] insert(a) print(a) output [30, 1, 2, 3, 4, 5]
  • 27. List Practice 1.list=[‘p’,’r’,’I’,’n’,’t’] print list[-3:] Ans: Error, no parenthesis in print statement. 2.Listout built-in functions. Ans: max(3,4),min(3,4),len(“raj”),range(2,8,1),round(7.8),float(5),int(5.0) 3.List is mutable-Justify Ans: List is an ordered sequence of items. Values in the list are called elements/items. List is mutable. i.e. Values can be changed. a=[1,2,3,4,5,6,7,8,9,10] a[2]=100 print(a) -> [1,2,100,4,5,6,7,8,9,10]
  • 28. Advanced list processing List Comprehension  List comprehensions provide a brief way to apply operations on a list.  It creates a new list in which each element is the result of applying a given operation in a list.  It consists of brackets containing an expression followed by a “for” clause, then a list.  The list comprehension always returns a result list. Syntax list=[ expression for item in list if conditional ]
  • 29. Advanced list processing . List Comprehension output >>>L=[x**2 for x in range(0,5)] >>>print(L) [0, 1, 4, 9, 16] >>>[x for x in range(1,10) if x%2==0] [2, 4, 6, 8] >>>[x for x in 'Python Programming' if x in ['a','e','i','o','u']] ['o', 'o', 'a', 'i'] >>>mixed=[1,2,"a",3,4.2] >>> [x**2 for x in mixed if type(x)==int] [1, 4, 9] >>>[x+3 for x in [1,2,3]] [4, 5, 6] >>> [x*x for x in range(5)] [0, 1, 4, 9, 16] >>> num=[-1,2,-3,4,-5,6,-7] >>> [x for x in num if x>=0] [2, 4, 6] >>> str=["this","is","an","example"] >>> element=[word[0] for word in str] >>> print(element) ['t', 'i', 'a', 'e']
  • 30. Nested list  List inside another list is called nested list. Example >>> a=[56,34,5,[34,57]] >>> a[0] 56 >>> a[3] [34, 57] >>> a[3][0] 34 >>> a[3][1] 57
  • 31. Tuple  A tuple is same as list, except in parentheses instead of square brackets.  A tuple is an immutable list. i.e. can not be changed.  Tuple can be converted into list and list can be converted in to tuple. Benefit:  Tuples are faster than lists.  Tuple can be protected the data.  Tuples can be used as keys in dictionaries, while lists can't. Operations on Tuples: 1. Indexing 2. Slicing 3. Concatenation 4. Repetitions 5. Membership 6. Comparison
  • 32. Tuple  . Operations Example Description Creating a tuple >>>a=(20,40,60,”raj”,”man”) Creating the tuple with different data types. Indexing >>>print(a[0]) 20 Accessing the item in the position 0 Slicing >>>print(a[1:3]) (40,60) Displaying elements from 1st to 2nd. Concatenation >>> b=(2,4) >>>print(a+b) >>>(20,40,60,”raj”,”man”,2,4) Adding tuple elements. Repetition >>>print(b*2) >>>(2,4,2,4) Repeating the tuple Membership >>> a=(2,3,4,5,6,7,8,9,10) >>> 5 in a True >>> 2 not in a False If element is present in tuple returns TRUE else FALSE Comparison >>> a=(2,3,4,5,6,7,8,9,10) >>>b=(2,3,4) >>> a==b False If all elements in both tuple same display TRUE else FALSE
  • 33. Tuple Tuple methods  Tuple is immutable. i.e. changes cannot be done on the elements of a tuple once it is assigned. Methods Example Description tuple.index(element) >>> a=(1,2,3,4,5) >>> a.index(5) 4 Display the index number of element. tuple.count(element) >>>a=(1,2,3,4,5) >>> a.count(3) 1 Number of count of the given element. len(tuple) >>> len(a) 5 The length of the tuple min(tuple) >>> min(a) 1 The minimum element in a tuple max(tuple) >>>max(a) 5 The maximum element in a tuple del(tuple) >>>del(a) Delete the tuple.
  • 34. Tuple Convert tuple into list Convert list into tuple Methods Example Description list(tuple) >>>a=(1,2,3,4,5) >>>a=list(a) >>>print(a) [1, 2, 3, 4, 5] Convert the given tuple into list. Methods Example Description tuple(list) >>> a=[1,2,3,4,5] >>> a=tuple(a) >>> print(a) (1, 2, 3, 4, 5) Convert the given list into tuple.
  • 35. Tuple Tuple Assignment  Tuple assignment allows, variables on the left of an assignment operator and values on the right of the assignment operator.  Multiple assignment works by creating a tuple of expressions from the right hand side, and a tuple of targets from the left, and then matching each expression to a target.  It is useful to swap the values of two variables. Example: Swapping using temporary variable Swapping using tuple assignment a=20 b=50 temp=a a=b b=temp print("value after swapping is",a,b) a=20 b=50 (a,b)=(b,a) print("value after swapping is",a,b)
  • 36. Tuple Multiple assignments  Multiple values can be assigned to multiple variables using tuple assignment. Example >>>(a,b,c)=(1,2,3) >>>print(a) 1 >>>print(b) 2 >>>print(c) 3
  • 37. Tuple Tuple as return value  A Tuple is a comma separated sequence of items.  It is created with or without ( ).  A function can return one value.  if you want to return more than one value from a function then use tuple as return value. Example: Program to find quotient and reminder output def div(a,b): r=a%b q=a//b return(r,q) a=eval(input("enter a value:")) b=eval(input("enter b value:")) r,q=div(a,b) print("reminder:",r) print("quotient:",q) enter a value:5 enter b value:4 reminder: 1 quotient: 1
  • 38. Tuple Tuple as argument  The parameter name that begins with * gathers argument into a tuple. Example def printall(*args): print(args) printall(2,3,'a') Output: (2, 3, 'a')
  • 39. Dictionaries  Dictionary is an unordered collection of elements.  An element in dictionary has a key:value pair.  All elements in dictionary are placed inside the curly braces i.e. { }  Elements in Dictionaries are accessed via keys.  The values of a dictionary can be any data type.  Keys must be immutable data type. Operations on dictionary 1. Accessing an element 2. Update 3. Add element 4. Membership
  • 40. Dictionaries  . Operations Example Description Creating a dictionary >>> a={1:"one",2:"two"} >>> print(a) {1: 'one', 2: 'two'} Creating the dictionary with different data types. Accessing an element >>> a[1] 'one' >>> a[0] KeyError: 0 Accessing the elements by using keys. Update >>> a[1]="ONE" >>> print(a) {1: 'ONE', 2: 'two'} Assigning a new value to key. Add element >>> a[3]="three" >>> print(a) {1: 'ONE', 2: 'two', 3: 'three'} Add new element in to the dictionary with key. Membership a={1: 'ONE', 2: 'two', 3: 'three'} >>> 1 in a True >>> 3 not in a False If the key is present in dictionary returns TRUE else FALSE
  • 41. Dictionaries Methods in dictionary Method Example Description Dictionary.copy() a={1: 'ONE', 2: 'two', 3: 'three'} >>> b=a.copy() >>> print(b) {1: 'ONE', 2: 'two', 3: 'three'} copy dictionary ’a’ to dictionary ‘b’ Dictionary.items() >>> a.items() dict_items([(1, 'ONE'), (2, 'two'), (3, 'three')]) It displays a list of dictionary’s (key, value) tuple pairs. Dictionary.key() >>> a.keys() dict_keys([1, 2, 3]) Displays list of keys in a dictionary. Dictionary.values() >>> a.values() dict_values(['ONE', 'two', 'three']) Displays list of values in a dictionary. Dictionary.pop(key ) >>> a.pop(3) 'three' >>> print(a) {1: 'ONE', 2: 'two'} Remove the element with key.
  • 43. Comparison of List, Tuples and Dictionary . List Tuple Dictionary A list is mutable A tuple is immutable A dictionary is mutable Lists are dynamic Tuples are static Values can be of any data type and can repeat. Keys must be of immutable type Homogenous Heterogeneous Homogenous Slicing can be done Slicing can be done Slicing can't be done
  • 44. Assignment 1.Addition of matrix 2.Multiplication of matrix 3.Transpose of matrix 4.Selection sort 5.Insertion sort 6.Merge sort 7.Histogram email:mrajen@rediffmail.com
  • 45. .