Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views

Python Unit 3

Uploaded by

A random girl
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Python Unit 3

Uploaded by

A random girl
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 99

Python Application Programming

(15CS664) : Open Elective


Module : III , Class : 6A
Manju S,
AP/CSE,
CMRIT,
Bangalore
Topics
 Lists
 Dictionaries
 Tuples
 Regular Expressions
Data structures in Python
 How data are organized easily ?
 Lists
 Dictionaries
 Tuples
 Sets
Immutable vs. Mutable
Immutable Mutable
 Numbers  Lists
 Strings  Dictionaries
 Tuples  Sets
 Values of variables cannot  Values of variables can be
be changed once assigned, changed without changing
if at all it gets changed then the id of the variable
its id would be different
Lists
 List is a sequence of values of any type i.e. need not be of same
type even different types are allowed
 Values in the list is called as elements or items that can be accessed
using indexing
 List representation : [ ]
 E.g:
 L=[1,2,3,4] # list of 4 integers
 L=[‘abc’, ‘fd’]# list of 2 strings
 L=[1,2,45.6, ‘hello’] #list of 2 integers, 1 float and 1 string
Lists are mutable
 The items/values of the list can be changed
 E.g.:

L=[1,2,3,4]
 The item assignment L[2]=30 is possible since its mutable
Traversing a list
st=[1,2,3,4]
for i in st:
print(i)
 The above code produces output like
1
2
3
4
Traversing a list by indexing
 E.g.:
fruit=[“apple”, “orange”, “banana”]
for index in range(len(fruit)):
print(fruit[index])
 The above code produces output like
apple
orange
banana
Guess the Output
Code : Code:
Empty=[] List=[1,2,3,[‘a’, ‘b’, ‘c’],4.5]
for i in Empty: print(len(List))
print(i)

 If the list is empty then the  Length will be 5 because the


loop fails and the statements sub-list/nested list is also
doesn’t execute considered as an item/value
of list
List operations
 + operator upon two lists concatenates them
E.g.:
l1=[1,2,3]
l2=[5,6,7]
print(l1+l2)
 Output would be [1,2,3,5,6,7]
List operations
 * on list repeats the list
E.g.:
l1=[1,2,3]
print(l1*3)
 Output would be [1,2,3,1,2,3,1,2,3]
List slicing
 Slicing extracts the elements specified from the list
l=[1,2,3,4,5,6,7,8]
print(l[1:3])
print(l[ : 5])
print(l[5: ])
print(l[ : ])
 If starting index is not specified its starts from 0 and if ending index is
not specified then its ends at last index, if both are not specified then it
prints the original list
List methods : append
 Syntax : list_name.append(element to be appended)
 E.g.:

l1=[1,2,3]
l1.append(4)
print(l1)
 The above code outputs the list [1,2,3,4]
List methods : extend
 Extend appends a list to another list
 Syntax : list_name.extend(list to be appended)

 E.g.:

l1=[1,2,3]
l2=[4,5,6]
print(l1.extend(l2))
 The above code outputs the list [1,2,3,4,5,6]
List methods : sort
 Sorts the list
 Syntax : list_name.sort( )  ascending order

 list_name.sort(reverse=True )  descending order

 E.g.:

l1=[3,1,2]
print(l1.sort())
 The above code outputs the list [1,2,3]
List methods : reverse
 Reverses the elements of the list
 Syntax : list_name.reverse( )

 E.g.:

l1=[3,1,2]
print(l1.reverse())
 The above code outputs the list [2,1,3]
List methods : pop
 Remove the item at the given position in the list, and return it.
If no index is specified, a.pop() removes and returns the last
item in the list .
 Syntax : list_name.pop(index )
List methods : Other methods
 Count : Syntax : list.count(a) counts for a in the list and returns
the count
 Insert : Syntax : list.insert(i,a) inserts a element at I th index of
list
 Remove :Syntax : list.remove(x) Remove the first item from
the list whose value is equal to x
 Clear : Syntax: list.clear() removes all the elements from list
Programming Exercise : Lists
Consider a list (list = []). You can perform the following commands:
1.insert i e: Insert integer at position .
2.print: Print the list.
3.remove e: Delete the first occurrence of integer .
4.append e: Insert integer at the end of the list.
5.sort: Sort the list in descending order.
6.pop: Pop the last element from the list.
7.reverse: Reverse the list.
Initialize your list and read in the value for the same. Write a menu driven program to
execute the operations of list.
Programming Exercise
 Program to find second largest number from a list without
using built in functions except length.
 Program to sort 2 lists given by user and merge it.
Deleting elements in list
 How to delete multiple elements from a list using index?
 pop takes one index at a time to delete (Iteration can be done)

 Remove cannot be used as it takes the element to be deleted

 del can be used

t=[1,2,3,4,5,6]
del t[1:5]
print(t)
 Output would be [1]
Lists and functions
 There are a number of built in functions that can be used on lists
 E.g.:

li=[1,2,3,4]
print(len(li))
print(max(li))
print(min(li))
print(sum(li))
print(sum(li)/len(li))
Lists and Strings : Conversion : String to list
 List is sequence of values
 Strings is a sequence of characters

 But still we cant call a list of characters as string

 How to convert a string into list? i.e list of characters

 By typecasting using built in method list()

a=“python” #a string
b=list(a)
print(a) # list of characters
List and Strings : Conversion : String to list
 List functions breaks a string into individual letter
 How to break a string into a list individual words?

 By using Split() method

s=“the monk”
a=s.split( )
print(a)
 Output would be [‘the’ , ‘monk’]
Lists and Strings : Conversion : list to string
 From string to list we used split and or the vice versa we can use join()
string method that concatenates a list of strings
 join() is the inverse of split()

t=[‘hello’, ‘how’, ‘ r’, ‘ yu’]


delimiter= “ ” # a string holding a single space
delimiter.join(t) # as join is a string method it should be
called as string.join(“list_to_be_joined”)
 Output would be a string ‘hello how r yu’

 Delimiter is the boundary for the words. Here the list of words is joined
with a delimiter space.
Parsing Lines : Programming exercise
 Input file format:
From stephen.mrquet@uct.ac.za Sat Jan 5 09:14:16 2006
hello sun
From stephen.mrquet@uct.ac.za Sun Jan 6 09:14:16 2006
The monk who sold his Ferrari Wed
from blahblah@uct.ac.za Mon Jan 7 10:12:13 2008
 Write a python program to parse the lines and print the day on which the activity
was recorded. By default the activity will be recorded in the following format
 From mailid day Month date time

 Output should be:

Sat
Parsing through lines of a file
f=open("b.txt",'r')
for line in f:
if not line.startswith("From") :
continue
words=line.split()
print(words[2])
Programming Exercise
 Write a python Program to swap the first and last element of a
list and print swapped elements in a new list
 Write a python code to swap the first even number in the list
with the third odd number of the same list.
Objects and values
 Having two strings a=“hello” and b=“hello” i.e. the same value
whether a and b will refer to two different objects having same
value or a single object holding that value?
a “hello” a
”hello”
b “hello” or b
 That can be checked using ‘is’ operator i.e a is b

 a is b will return True i.e. both a and b points to same object


having same value
Objects and values
 When the same scenario is discussed for lists, False will be
returned
 i.e two lists having same identical elements will not be
pointing to a same object.
Aliasing
 In case if the following statements are executed
a=[1,2,3]
b=a
print(a is b)
 This will return true as the output because in this case the
variables refer to a single object that refers to same elements
 When an object with more than one reference has more than
one name, ten we call hat object to be aliased
Aliasing : Guess the output
 Guess the output
a=[1,2,3]
b=a
a[1]=20
print(b[1])
 If the aliased object is mutable, then changes made to one
variable will reflect another variable as well
List arguments
 List can be passed as an argument to function
What about l and list
 E.g: variables?
Aliased or not?
def delhead(l): Yes it will be a single
aliased object
l.pop(0)
list=[1,2,3]
delhead(list)
print(list)
 The above code will produce output [2,3]

 Changes made to formal are reflected back in actual


Guess the output
t1=[1,2] t1=[1,2]
t2=t1.append(3) t2=t1 + [3]
print(t1) print(t1)
print(t2) print(t2)
 The output would be  The output would be

[1,2,3] [1,2]
None [1,2,3]
 As append returns None  + creates a new list while
append modifies a list
Programming exercise
 Write a user defined function chop() that takes list as the input
and chops the first and last element of the list
 Write a program to open a file and to read it line by line. For
each word read check whether the list has that word already. If
the list has that word ignore else add it to list. When the
program completes, the words of the file read should be
displayed in sorted order.
Dictionaries
 Dictionaries are collection of elements
 They are like lists having index positions of any almost any
type wherein lists have only integer as index positions
 Dictionary is mapping between set of indices (called keys) and
a set of values which is mutable
 Each key maps to a value and hence it is called as key value
pair
 Representation : { } where key and value are separated by
colon
Dictionaries
 E.g.: Varied indices
d={ 1: ‘a’,2 : ‘b’}
 dictionary with 1 and 2 as indices and a and b as value

d={1.1 : ‘a’, 1.2 : ‘b’}


 dictionary with 1.1 and 1.2 as indices and a and b as value

d={ ‘a’ : 1, ‘b’ :2}


 dictionary with ‘a’ and ‘b’ as indices and 1 and 2 as value

d={‘abc’ :12, ‘bcd’ : 13}


 dictionary with ‘abc’ and ‘bcd’ as indices and 12 and 13 as value
Dictionaries
 dict() is the built in method to create an empty dictionary
 E.g:

a=dict()
a[‘ab’]=1
a[‘bc’]=2
print(a)
 To add elements to dictionary square brackets can be used.

 The order of key value pairs in the dictionary may vary that doesn’t
matter
Dictionaries
 len( ) function returns the number of key value pairs in a
dictionary
 in operator checks for the existence of keys in dictionaries

 E.g.:

d={1: ‘a’,2:’b’, ‘c’:3}


print(b in d)
print(1 in d)
 False and True will be returned
Dictionaries
 To get only the keys from dictionary keys() function an be used which
returns a list of keys
 To get only the values from dictionary values() function an be used
which returns a list of values
 E.g.:

d={1: ‘a’, 2: ‘b’ , ‘c’ :3}


print(d.keys())
print(d.values())
print (‘c’ in d.values())
 Output would be list of keys and values followed by False
Programming Exercise :
Dictionary as a set of counters
 Write a python code to read a string and to give the frequency
of character occurrence in that string.
 3 possible solutions
 Create 26 possible variables and have a counter for those variables
 Create a list with 26 elements and then change the element of list
thereby incrementing for the count of each word
 Create a dictionary having words as index and count as values
Programming Exercise :
Dictionary as a set of counters
str=“hellooooooo”
d=dict()
for i in str:
if i in d:
d[i]=d[i]+1
else:
d[i]=1
print(d)
Get() method in Dictionaries
 get(‘key’, ‘default_value’) method of dictionary takes a key
and a default value. If the key appears in the dictionary it
returns the actual value of the key else it returns the default
value
 E.g.:

d={‘a’:1,’b’:2}
print(d.get(‘c’,0))
print(d.get(‘b’,0)
 Output produced would be 0 and 2
Modifying the counter program using get()
str=“hellooooooo”
d=dict()
for i in str:
d[i] = d.get(i,0) + 1
print(d)
Dictionaries and files : Programming Exercise
 Most common use of dictionary is to count the occurrence of
words in a file.
 Write a python code to read through the lines of file and to
print the count of occurrence of each word
 Write a python code to read through the lines of file and to
print the count of occurrence of each character in the file
Word count in file
f=open(“a.txt”,”r”)
dic=dict()
for i in f:
a=i.split()
for j in a:
if j in dic:
dic[j]=dic[j]+1
else:
dic[j]=1
print(dic)
Letter count in file
f=open("a.txt","r")
dic=dict()
for i in f:
a=i.split()
for j in a:
letters=list(j)
for k in letters:
if k in dic:
dic[k]=dic[k]+1
else:
dic[k]=1
print(dic)
Looping and Dictionaries
 When a dictionary is iterated through any loops then the
iteration variable gets iterated through keys
 E.g.:

dic={‘a’:1,’b’:2,’c’:3}
for i in dic:
print(i)
print(dic[i])
Programming exercise
 Assume a dictionary having string data as the keys. Sort the
keys and print the dictionary
c={“bc”:34, “ab” :12}
l=list(c.keys())
l.sort()
for k in l:
print(k,c[k])
Advanced text parsing
 Write a python code to read through the lines of file and to
print the count of occurrence of each word by omitting all the
punctuations present in the file.
 Note : Give the word count irrespective of the upper/lower
case e.g.: Soft and soft to be counted as same word
Translate method
 str.translate(str.maketrans(fromstr, tostr, deletestr))
 Replace the characters in fromstr with the character in tostr
and delete all the characters in deletestr.
 fromstr and tostr can be even empty string and deletestr is
optional.
 maketrans: generates a mapping table/translation table
 translate: Translates according to the table generated by
maketrans
Removing Punctuations
import string
f=open(“a.txt”,’r’)
count=dict() for i in words:
for str in f: if i not in count:
str=str.rstrip() count[i]=1
str=str.translate(str.maketransl else:
ate(‘‘, ‘‘, string.punctuation)) count[i]+=1
str=str.lower() print(count)
words=str.split()
Programming exercise
 Write a python code to create a dictionary that has letters(a..z,
A...Z) as keys and its corresponding ASCII codes as values.

 Hint : To create a dictionary of alphabets


 D=dict.fromkeys(string.ascii_lowercase) can have one more
argument also specifying the default value for keys
 Merging two dictionaries : dictionary1.update(dictionary2)
ASCII Values – Program 1
my_dict = dict()
for alpha in range(0, 26):
my_dict[chr(alpha+65)] = alpha+65 #upper case
my_dict[chr(alpha+97)] = alpha+97 #lower case
print(my_dict)
ASCII Values – Program 2
import string
d1=dict.fromkeys(string.ascii_lowercase)
d2=dict.fromkeys(string.ascii_uppercase)
d1.update(d2)
for i in d1:
d1[i]=ord(i)
print(d1)
Tuples
 Sequence of values much like a list indexed by integers
 Can have values of any type

 Tuples are immutable.

 E.g.:

T=1,2,3,4,5,6 #() is not required


T=(1,2,3,4,5,6)
T=(“A”,32,45.0)
Tuples : proper assignments
 T=(‘a’) or T=(1)
 The above assignment will be recognized by python as
expression having string type and integer type data when your
tuple has single element
 In such case use a comma at the end to make python
understand that T is a tuple
 T=(‘a’,) or T=(1,)
Creating empty tuples
 T=() # creates an empty tuple
 T=tuple() #creates an empty tuple
 tuple() method can also be used for typecasting a sequence
(string,dictionary,list) of data into tuple.
Indexing and Slicing
 To access each and every element of a tuple indexing ca be
used.
 Slicing in tuples is similar to slicing in lists.
 T=(1,2,3,4,5,6)
 T[0] return the first element
 T[2:4] returns 3,4
Comparison of tuples
 Can be done by < , > etc.,
 E.g.:
 (1,2,3) < (2,3,4) will return True
 (1,2,3)>(2,4,1) will return False
 Comparison starts from the first element of both sequences and
moves ahead
DSU Pattern : List of tuples
 Assume you are given with txt = 'but soft what light in yonder
window breaks'
a list of words and you want
words = txt.split()
to sort them from longest to t = list()
shortest for word in words:
 Decorate t.append((len(word), word))
t.sort(reverse=True)
 Sort
res = list()
 Undecorate for length, word in t:
res.append(word)
print res
Tuple assignment
 Tuple can be used on the left side of an assignment statement
 Hence it allows us to assign more than one variable at a time
when left side is a sequence
 E.g:

m=[‘a’,’b’]
(x,y)=m
print(x,y)
 Assignments work like x=m[0] and y=m[1]
Tuple assignment
 Swapping two values in a single statement
 i.e. x, y=y, x swapping is allowed

 Both left and right side are tuples of variables and tuples of expressions

 x,y=1,2,3 will throw a value error since it has too man values

E.g.:
a=help@abc.in
x,y=a.split(‘@’)
 x holds help and y holds abc.in
Dictionaries and tuples
 Dictionaries have a method called items that returns a
sequence of tuples where each tuple is key value pair
d={‘b’:10, ‘a’:20, ‘c’:30}
li=list(d.items())
print(li) #li is the list of tuples
li.sort()
print(li)
Multiple assignment with dictionaries
 Traversing the keys and values of a dictionary in a single loop
d={‘b’:10, ‘a’:20, ‘c’:30}
for key, val in list(d.items()):
print(key, val)
Sorting dictionaries based on values
d={‘b’:10, ‘a’:20, ‘c’:30}
li=list()
for key, val in list(d.items()):
li.append((val,key))
li.sort(reverse=True)
Programming exercise
 Write a python code to display the most commonly used words
of a file using dictionaries and tuples.
 Assume the words having highest count of occurrences are the
common words
Identifying the common words in a file
import string for word in words:
fhand = open(‘a..txt') if word not in counts:
counts = dict() counts[word] = 1
for line in fhand: else:
line = line.translate(‘’, ‘’, counts[word] += 1
string.punctuation) lst = list()
line = line.lower() for key, val in counts.items():
words = line.split() lst.append( (val, key) )
lst.sort(reverse=True)
for key, val in lst[:10] :
print (key, val)
Using tuples as keys in dictionaries
 E.g.: Telephone Directory where a number can be mapped with
both last and first name of a person
dir={(‘jack’,’jonas’): 1232, (‘ram’,’kumar’):3565}
print(dir[‘jack’,’jonas’]) # prints 1232
for first,last in dir: # traversing through all items
print(first,last,dir[first,last])
Regular Expression
 A regular expression is a special sequence of characters that
helps you match or find other strings or sets of strings, using a
specialized syntax held in a pattern
 Regular expressions are useful for string and pattern matching,
searching strings etc.,
 Module name : re
Character and its special sequence
a, X, 9, <
1
ordinary characters just match themselves exactly.
. (a period)
2
matches any single character except newline '\n'
\w
3
matches a "word" character: a letter or digit or underbar [a-zA-Z0-9_].
\W
4
matches any non-word character [Symbols, white space etc.,].
\b
matches word which has specified characters present at starting or ending of a string
5
e.g.: “\bsu” will search and match word starting with su
“ly\b” will match word that ends with ly
\B
matches word which has specified characters but not at starting or ending of string
6
e.g.: “\bsu” will search and match word having su but not starting with su
“ly\b” will match word that has ly but not ending with ly
Character and its special sequence
\S
7
matches any non-whitespace character.
\t, \n, \r
8
tab, newline, return
\d
9 decimal digit [0-9]
‘\d’ matches strings having digits
^
10 matches start of the string
‘^hello’ matches strings starting with hello
$
11 match the end of the string
‘book$’ matches strings ending with book
\s
12 matches a single whitespace character -- space, newline, return, tab
Basic Expressions in RE
 [x] matches any one of a list of characters:
 “[abc]” matches ‘a’,’b’, or’c’
 [^x] matches any one character that is not in x
 “[^abc]” matches any single character except ‘a’,’b’,’c’
 “.” matches any single character
 {} Exactly the specified number of occurrences
 “al{2}” matches all
 Parentheses can be used for grouping
 “(abc)+ matches ‘abc’,’abcabcabc’,etc.,
Basic expressions in RE
 [a-z] matches any lower case character between a to z
 x|y matches x or y
 “here|there” matches ‘here’ or ‘there’ but not ‘herethere’
 X* matches zero or more x’s
 “d*” matches ‘ ‘,’d’,’dd’,’ddd’,…etc
 X+ matches one or more x’s
 “d+” matches ’d’,’dd’,’ddd’,…etc
 X? matches zero or one x’s
 “d?” matches ‘ ‘ or ’d’
RE
 Write a RE that matches all words starting with A
 Write a RE that matches indian phone number
 Write a RE to match any word having exactly 2 vowels in it

 ^A[a-z]*
 0[6|7|8|9][0-9]{10}
 \S*[aeiou]\S*[aeiou]\S*
Basic Functions in RE
 Re.search()
 Re.findall()

Content Beyond Syllabus


 Re.match()

 Re.sub()

 Re.compile()
Search in RE
 Search is the most commonly used function in re
 Syntax: search(“text_to_search”, “string”)
 Returns a match object for the first match if match is found
import re
hand = open(‘a.txt')
for line in hand:
line = line.rstrip()
if re.search(‘^From:', line) :
print line
 This works like a normal find() will work. Real power of RE comes when we want
to search for special characters in some patterns
Character matching in RE
 Period / full stop/dot : matches with any character
 E.g.: F..m: can match to From:/ Faom:/F12m:/F!@m: etc.,
import re
hand = open(‘a.txt')
for line in hand:
line = line.rstrip()
if re.search('F..m:', line):
print line
Repetition
 The dot operator can become more powerful when combined
with * or +
 * - Zero or more characters , + - one or more characters
 * and + applies to the single character which is present to its
left
import re
hand = open(‘a.txt')
for line in hand:
line = line.rstrip()
if re.search('From:.+@', line):
print line
Extracting data using RE : findall
 findall() of RE can be used to search for a substring and to
extract it from string
 Syntax :
 findall(“Regular_Expression”, “string_in_which_to_search”)
 Returns a list of matched substring/string
Extracting data using RE
 Extract mail ids from string
 Use ‘\S’ that match single non white space character
 E.g.:
import re
s = “Hello from csev@umich.edu to cwen@iupui.edu about the meeting
@2PM”
lst = re.findall('\S+@\S+\.\S', s)
print(lst)
Sub in RE
 re.sub(): used to replace substrings
 Syntax: re.sub(pattern,replacement_string,string)
import re
s=“ apple banana mango”
re.sub(“a[a-z]+”, “fruit”,s)
print(s)
Match in RE
 Match looks for the matching string from beginning of string
 Re.search-> search looks for a pattern anywhere in a string
 Syntax: re.search(pattern,string)
 Re.match->match looks for a match starting from the
beginning of the string
 Syntax: r[/e.match(pattern,string)
 Match object is returned if match exists else nothing is
returned
Compile in RE
 Re.compile() : compiles a regular expression pattern into
pattern object which can be used for matching in future
 Syntax: re.compile(regexp)
 Converting expression into object makes searching easier
whenever we want to search for a string repeatedly
import re
s=“hello how are you”
a=re.compile(“^h[a-z]{4}”)
a.match(s)
Compile in RE
 The statement re.match((“^h[a-z]{4}”,s) is equivalent to
import re
s=“hello how are you”
a=re.compile(“^h[a-z]{4}”)
a.match(s)
Guess the RE
 Write a RE to match the CMRIT mail id
 RE is ‘[a-z0-9_]+@cmrit\.ac\.in’
Escape character
 Sometimes we may have to check for the existence of
characters like . or $ etc., in the string.
 When we simply mention that the python interpreter will
match dot(.) with any non white space character and it wont
match the actual dot.
import re
s=“ google.in blah blah airindia.in pumpkin”
re.findall(‘[a-z0-9].in’,s)
 Will return google.in, airindia.in and pumpkin
Escape character
 In order to represent dot(.) as a symbol use a slash before it.
import re
s=“ google.in blah blah airindia.in pumpkin”
re.findall(‘[a-z0-9]\.in’,s)
 Will return google.in, airindia.in
 Pumpkin will be omitted because \ is used before dot makes
interpreter to read dot as just a symbol dot rather that getting
replaced with non white space characters
Programming Exercise
 Write a python code using RE to print words of an input file
that starts with vowels
 Write a python code using RE to find and replace a word in a
list of words with a string given by user
 RE is ‘\b[aeiou]+[a-z]*’
 re.sub() method shall be used
Programming Exercise
 Write a program to look for lines of the form
New_Marks : 98
and extract the number from each of the lines using a RE and
findall() method. Compute the average and print the same.
Solution
import re
f=open("a.txt","r")
sum,count=0,0
for i in f:
i=i.rstrip()
if(re.findall("^New_Marks:[0-9]+",i)):
i=i[10:]
count=count+1
sum=sum+int(i)
print(sum,sum/count)
Just to know!
Nested Lists
 When a list is given as an element of another list we called it
as nested lists
 E.g.: lis=[[1,2,3],[8,5],[3,4]]
 A list having list of numbers as an element
Traversing through nested lists
lis=[[1,2,3],[8,5],[3,4]]
for i in lis:
print(i)
for i in lis:
for j in i: #traverses through the inner list
print(j)
sorted() : Guess the Output
lis=[[1,2,3],[8,5],[3,4]]
print(sorted(lis))
print(sorted(lis,reverse=True)) [[1,2,3],[3,4],[8,5]]
[[8,5],[3,4],[1,2,3]]
print(sorted(lis,key=len))
[[3,4],[8,5],[1,2,3]]
print(sorted(lis,key=len,reverse=True)) [[1,2,3],[3,4],[8,5]]
print(lis) [[1,2,3],[8,5],[3,4]]
Sorted() function
 sorted(seq, key, reverse)
 seq :Sequence of elements to be sorted (List/String/Tuple etc.,)
 key : function based on which sorting is done
 reverse : if enabled True returns list in descending order
 Return Type : List of sorted elements
Difference between sort() and sorted()
 sort changes the original list
 sorted() returns the new list keeping the original sequence
unedited
 Hence sorted() is slower compared to sort()
 Incase of immutable data types sorted() can be used to sort as
they don’t have sort function.
References:
1. Charles R Severance, “Python for Everybody: Exploring Data
Using Python 3”, 1st edition, CreateSpace Independent
Publishing platform, 2016.
2. Allen B. Downey, “Think Python: How to think like a
Computer Scientist”, 2nd edition, Green Tea press, 2015.
3. Python documentation

09-04-2019 99
Thank You

09-04-2019 100

You might also like