SlideShare ist ein Scribd-Unternehmen logo
1 von 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
.

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
 
Python
PythonPython
Python
 
Stacks in DATA STRUCTURE
Stacks in DATA STRUCTUREStacks in DATA STRUCTURE
Stacks in DATA STRUCTURE
 
Loops in Python
Loops in PythonLoops in Python
Loops in Python
 
Values and Data types in python
Values and Data types in pythonValues and Data types in python
Values and Data types in python
 
Python variables and data types.pptx
Python variables and data types.pptxPython variables and data types.pptx
Python variables and data types.pptx
 
Ip addressing
Ip addressingIp addressing
Ip addressing
 
Strings
StringsStrings
Strings
 
Singly link list
Singly link listSingly link list
Singly link list
 
Python Data-Types
Python Data-TypesPython Data-Types
Python Data-Types
 
Chapter 0 Python Overview (Python Programming Lecture)
Chapter 0 Python Overview (Python Programming Lecture)Chapter 0 Python Overview (Python Programming Lecture)
Chapter 0 Python Overview (Python Programming Lecture)
 
Pointers in c++ by minal
Pointers in c++ by minalPointers in c++ by minal
Pointers in c++ by minal
 
Linked list
Linked listLinked list
Linked list
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 
Singly & Circular Linked list
Singly & Circular Linked listSingly & Circular Linked list
Singly & Circular Linked list
 
String Manipulation in Python
String Manipulation in PythonString Manipulation in Python
String Manipulation in Python
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 
Data Structures- Part7 linked lists
Data Structures- Part7 linked listsData Structures- Part7 linked lists
Data Structures- Part7 linked lists
 
Bca ii dfs u-2 linklist,stack,queue
Bca ii  dfs u-2 linklist,stack,queueBca ii  dfs u-2 linklist,stack,queue
Bca ii dfs u-2 linklist,stack,queue
 
Stacks, Queues, Deques
Stacks, Queues, DequesStacks, Queues, Deques
Stacks, Queues, Deques
 

Ähnlich wie Python Beginners Guide Install Ubuntu Python3

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
 

Ähnlich wie Python Beginners Guide Install Ubuntu Python3 (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
 

Mehr von 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
 

Kürzlich hochgeladen

Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 

Kürzlich hochgeladen (20)

Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 

Python Beginners Guide Install Ubuntu Python3

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