Professional Documents
Culture Documents
Unit-2 Sem-V Python
Unit-2 Sem-V Python
Control Statements:
It is sometimes desirable to skip some statements inside the loop or terminate the
loop immediately without checking the test expression. In such cases we can
use break statements in Python. The break statement allows you to exit a loop from
any point within its body, bypassing its normal termination expression.
As seen in the above image, when the break statement is encountered inside a loop,
the loop is immediately terminated, and program control resumes at the next
statement following the loop.
break statement in while loop
n=1
while True:
print (n)
n+=1
if n==5:
break
print("After Break")
output:
After Break
In the above program, when n==5, the break statement executed and immediately
terminated the while loop and the program control resumes at the next statement.
break statement in for loop
if str == "t":
break
print(str)
output:
Continue statement works like break but instead of forcing termination, it forces
the next iteration of the loop to take place and skipping the rest of the code.
n=0
while n < 5:
n+=1
if n==3:
continue
print (n)
print("Loop Over")
output:
Loop Over
In the above program, we can see in the output the 3 is missing. It is because when
n==3 the loop encounter the continue statement and control go back to start of the
loop.
n=0
for n in range(5):
n+=1
if n==3:
continue
print(n)
print("Loop Over")
output
Loop Over
In the above program, we can see in the output the 3 is missing. It is because when
n==3 the loop encounter the continue statement and control go back to start of the
loop.
In Python, the pass keyword is used to execute nothing; it means, when we don't
want to execute code, the pass can be used to execute empty. It is the same as the
name refers to. It just makes the control to pass by without executing any code. If we
want to bypass any code pass statement can be used.
Suppose we have a loop, and we do not want to execute right this moment, but we
will execute in the future. Here we can use the pass.
pass
Example - 2:
for i in [1,2,3,4,5]:
if(i==4):
pass
print(i)
Output:
String Manipulation
String:
String – String represents group of characters. Strings are enclosed in double quotes
or single quotes. The str data type represents a String.
str1 = “Python”
Creating String
Single Quotes
str1 = ‘Python’
Double quotes
str2 = “Python”
Triple Single Quotes – This is useful to create strings which span into several lines.
Please Subscribe
Python’’’
Triple Double Quotes – This is useful to create strings which span into several lines.
Please Subscribe
Python ”””
Raw String – Row string is used to nullify the effect of escape characters.
Repetition operator is used to repeat the string for several times. It is denoted by *
Ex:-
“$” * 7
str1 * 5
Concatenation Operator
Ex:-
“Geeky” + “Shows”
str1 = “Geeky ”
str2 = “Shows”
str1 + str2
Comparing String
str1 = “GeekyShows”
str2 = “GeekyShows”
str1 = “GeekyShows”
str2 = “Python”
str1 = “A”
str2 = “B”
Slicing on String can be used to retrieve a piece of the string. Slicing is useful to
retrieve a range of elements.
Syntax:-
new_string_name = string_name[start:stop:stepsize]
If start and stop are not specified then slicing is done from 0th to n-1th elements.
Syntax:- string.upper( )
name = "python"
str1 = name.upper()
print(name)
print(str1)
Syntax:- string.lower( )
name = "PYTHON"
str1 = name.lower()
print(name)
print(str1)
3) swapcase ( ) – This method is used to convert all lower case character into
uppercase and vice versa.
Syntax:- string.swapcase ( )
name = "python"
str1 = name.swapcase()
print(name)
print(str1)
4) title ( ) – This method is used to convert the string in such that each word in
string will start with a capital letter and remaining will be small letter.
Syntax:- string.title ( )
str1 = name.title()
print(name)
print(str1)
5) isupper ( ) – This method is used to test whether given string is in upper case
or not, it returns True if string contains at least one letter and all characters are
in upper case else returns False.
Syntax:- string.isupper( )
name = "PYTHON"
str1 = name.isupper()
print(name)
print(str1)
6) islower ( ) – This method is used to test whether given string is in lower case
or not, it returns True if string contains at least one letter and all characters are
in lower case else returns False.
Syntax:- string.islower( )
name = "python"
str1 = name.islower()
print(name)
print(str1)
7) istitle ( ) – This method is used to test whether given string is in title format or
not, it returns True if string contains at least one letter and each word of the
string starts with a capital letter else returns False.
Syntax:- string.istitle( )
str1 = name.istitle()
print(name)
print(str1)
8) isdigit ( ) – This method returns True if the string contains only numeric digits
(0 to 9) else returns False.
Syntax:- string.isdigit()
name = "342343"
str1 = name.isdigit()
print(name)
print(str1)
9) isalpha ( ) – This method returns True if the string has at least one character
and all are alphabets ( A to Z and a to z) else returns False
Syntax:- string.isalpha()
name = "PYthon"
str1 = name.isalpha()
print(name)
print(str1)
10) isalnum ( ) – This method returns True if the string has at least one
character and all characters in the string are alphanumeric (A to Z, a to z and 0
to 9) else returns False
Syntax:- string.isalnum()
name = "PYthon2343"
str1 = name.isalnum()
print(name)
print(str1)
11) isspace ( ) – This method returns True if the string contains only space
else returns False.
Syntax:- string.isspace()
str1 = name.isspace()
print(name)
print(str1)
12) lstrip ( ) – This method is used to remove the space which are at left
side of the string.
Syntax:- string.lstrip()
str1 = name.lstrip()
print(name)
print(str1)
13) rstrip ( ) – This method is used to remove the space which are at right
side of the string.
Syntax:- string.rstrip()
str1 = name.rstrip()
print(name)
print(str1)
14) strip ( ) – This method is used to remove the space from the both side
of the string.
Syntax:- string.strip()
str1 = name.strip()
print(name)
print(str1)
15) replace ( ) – This method is used to replace a sub string in a string with
another sub string. Syntax:- string.replace(old, new)
name = "Python"
old = "Py"
new = "New"
print(name)
print(str1)
16) split ( ) – This method is used to split/break a string into pieces. These
pieces returns as a list.
Syntax:- string.split(‘separator’)
name = "Hello-how-are-you"
str1 = name.split('-')
print(name)
print(str1)
17) join ( ) – This method is used to join strings into one string.
Syntax:- “separator”.join(string_list)
str1 = "_".join(name)
print(name)
print(str1)
Syntax:- string.startswith(‘specified_string’)
str1 = name.startswith('Hi')
print(name)
print(str1)
19) endswith ( ) – This method is used to check whether a string is ending
with a substring or not. It returns True if the string ends with specified sub
string.
Syntax:- string.startswith(‘specified_string’)
str1 = name.endswith('Bye')
print(name)
print(str1)
String Methods::
1) center()
The center() method returns a string which is padded with the specified character.
center() Parameters
The fillchar argument is optional. If it's not provided, space is taken as default
argument.
The center() method returns a string padded with specified fillchar. It doesn't modify
the original string.
new_string = string.center(24)
Output:
Output:
2) zfill()
The zfill() method returns a copy of the string with '0' characters padded to the left.
zfill() Parameter
The width specifies the length of the returned string from zfill() with 0 digits filled to
the left.
zfill() returns a copy of the string with 0 filled to the left. The length of the returned
string depends on the width provided.
Suppose, the initial length of the string is 10. And, the width is specified 15. In this
case, zfill() returns a copy of the string with five '0' digits filled to the left.
Suppose, the initial length of the string is 10. And, the width is specified 8. In this
case, zfill() doesn't fill '0' digits to the left and returns a copy of the original string.
The length of the returned string in this case will be 10.
Example 1: How zfill() works in Python?
print(text.zfill(15))
print(text.zfill(20))
print(text.zfill(10))
Output
0program is fun
000000program is fun
program is fun
If a string starts with the sign prefix ('+', '-'), 0 digits are filled after the first sign prefix
character.
number = "-290"
print(number.zfill(8))
number = "+290"
print(number.zfill(8))
text = "--random+text"
print(text.zfill(20))
Output
-0000290
+0000290
-0000000-random+text
3) isidentifier()
The isidentifier() method returns True if the string is a valid identifier in Python. If not,
it returns False.
isidentifier() Paramters
str = 'Python'
print(str.isidentifier())
print(str.isidentifier())
str = '22Python'
print(str.isidentifier())
str = ''
print(str.isidentifier())
Output
True
False
False
False
• str = 'root33'
if str.isidentifier() == True:
else:
• str = '33root'
if str.isidentifier() == True:
else:
if str.isidentifier() == True:
else:
Output
4) count():
The count() method returns the number of occurrences of a substring in the given
string.
Example
count() method only requires a single parameter for execution. However, it also has
two optional parameters:
start (Optional) - starting index within the string where search starts.
end (Optional) - ending index within the string where search ends.
count() method returns the number of occurrences of the substring in the given
string.
# define string
substring = "is"
count = string.count(substring)
# print count
Output:
# define string
substring = "i"
# print count
Output:
Here, the counting starts after the first i has been encountered, i.e. 7th index position.
5) isprintable()
The isprintable() methods returns True if all characters in the string are printable or
the string is empty. If not, it returns False.
Characters that occupy printing space on the screen are known as printable
characters. For example:
digits
punctuation
whitespace
The syntax of isprintable() is:
string.isprintable()
isprintable() Parameters
True if the string is empty or all characters in the string are printable
s = 'Space is a printable'
print(s)
print(s.isprintable())
print(s)
print(s.isprintable())
s = ''
Space is a printable
True
False
s = chr(27) + chr(97)
if s.isprintable() == True:
print('Printable')
else:
print('Not Printable')
s = '2+2 = 4'
if s.isprintable() == True:
print('Printable')
else:
print('Not Printable')
Output:
Not Printable
Printable
6) casefold()
The casefold() method is an aggressive lower() method which converts strings to case
folded strings for caseless matching.
The casefold() method removes all case distinctions present in a string. It is used for
caseless matching, i.e. ignores cases when comparing.
For example, the German lowercase letter ß is equivalent to ss. However, since ß is
already lowercase, the lower() method does nothing to it. But, casefold() converts it
to ss.
string.casefold()
Output:
# ß is equivalent to ss
if firstString.casefold() == secondString.casefold():
else:
Output:
The expandtabs() method returns a copy of string with all tab characters '\t' replaced
with whitespace characters until the next multiple of tabsize parameter.
string.expandtabs(tabsize)
expandtabs() Parameters
The expandtabs() returns a string where all '\t' characters are replaced with
whitespace characters until the next multiple of tabsize parameter.
str = 'xyz\t12345\tabc'
# no argument is passed
# default tabsize is 8
result = str.expandtabs()
print(result)
Output
The position of first '\t' character in the above program is 3. And, the tabsize is 8 (if
argument is not passed).
The expandtabs() character replaces the '\t' with whitespace until the next tab stop.
The position of '\t' is 3 and the first tab stop is 8. Hence, the number of spaces after
'xyz' is 5.
The next tab stops are the multiples of tabsize. The next tab stops are 16, 24, 32 and
so on.
Now, the position of second '\t' character is 13. And, the next tab stop is 16. Hence,
there are 3 spaces after '12345'.
str = "xyz\t12345\tabc"
# tabsize is set to 2
# tabsize is set to 3
# tabsize is set to 4
# tabsize is set to 6
Output
Explanation
The default tabsize is 8. The tab stops are 8, 16 and so on. Hence, there is 5 spaces
after 'xyz' and 3 after '12345' when you print the original string.
When you set the tabsize to 2. The tab stops are 2, 4, 6, 8 and so on. For 'xyz', the tab
stop is 4, and for '12345', the tab stop is 10. Hence, there is 1 space after 'xyz' and 1
space after '12345'.
When you set the tabsize to 3. The tab stops are 3, 6, 9 and so on. For 'xyz', the tab
stop is 6, and for '12345', the tab stop is 12. Hence, there are 3 spaces after 'xyz' and
1 space after '12345'.
When you set the tabsize to 4. The tab stops are 4, 8, 12 and so on. For 'xyz', the tab
stop is 4 and for '12345', the tab stop is 12. Hence, there is 1 space after 'xyz' and 3
spaces after '12345'.
When you set the tabsize to 5. The tab stops are 5, 10, 15 and so on. For 'xyz', the tab
stop is 5 and for '12345', the tab stop is 15. Hence, there are 2 spaces after 'xyz' and
5 spaces after '12345'.
When you set the tabsize to 6. The tab stops are 6, 12, 18 and so on. For 'xyz', the tab
stop is 6 and for '12345', the tab stop is 12. Hence, there are 3 spaces after 'xyz' and
1 space after '12345'.
8) find()
In this tutorial, we will learn about the Python String find() method with the help of
examples.
The find() method returns the index of first occurrence of the substring (if found). If
not found, it returns -1.
Example
print(message.find('fun'))
# Output: 12
start and end (optional) - The range str[start:end] within which substring is searched.
If the substring exists inside the string, it returns the index of the first occurence of
the substring.
result = quote.find('small')
if (quote.find('be,') != -1):
else:
Output
Output
-1
-1
9
9) rfind()
The rfind() method returns the highest index of the substring (if found). If not found,
it returns -1.
rfind() Parameters
If substring exists inside the string, it returns the highest index where substring is
found.
result = quote.rfind('small')
result = quote.rfind('be,')
if (result != -1):
else:
Output
print(quote.rfind('things', 10))
print(quote.rfind('t', 2))
print(quote.rfind('th', 6, 20))
Output
-1
25
-1
18
10) index()
In this tutorial, we will learn about the Python index() method with the help of
examples.
The index() method returns the index of a substring inside the string (if found). If the
substring is not found, it raises an exception.
Example
result = text.index('is')
print(result)
# Output: 7
index() Syntax
index() Parameters
If substring exists inside the string, it returns the lowest index in the string where
substring is found.
The only difference is that find() method returns -1 if the substring is not found,
whereas index() throws an exception.
result = sentence.index('Java')
Output
result = sentence.index('Java')
ValueError: substring not found
Note: Index in Python starts from 0 and not 1. So the occurrence is 19 and not 20.
print(sentence.index('ing', 10))
print(sentence.index('fun', 7, 18))
Output
15
17
print(quote.index('fun', 7, 18))
The rindex() method returns the highest index of the substring inside the string (if
found). If the substring is not found, it raises an exception.
rindex() Parameters
If substring exists inside the string, it returns the highest index in the string where the
substring is found.
The only difference is that rfind() returns -1 if the substring is not found,
whereas rindex() throws an exception.
Example 1: rindex() With No start and end Argument
result = quote.rindex('small')
Output
result = quote.rindex('small')
print(quote.rindex('t', 2))
# Substring is searched in 'll things with'
print(quote.rindex('th', 6, 20))
Output
25
18
12 partition()
The partition() method splits the string at the first occurrence of the argument string
and returns a tuple containing the part the before separator, argument string and the
part after the separator.
string.partition(separator)
partition() Parameters()
The partition() method takes a string parameter separator that separates the string at
the first occurrence of it.
Return Value from partition()
the part before the separator, separator parameter, and the part after the separator if
the separator parameter is found in the string
the string itself and two empty strings if the separator parameter is not found
print(string.partition('is '))
print(string.partition('not '))
print(string.partition('is'))
Output
The rpartition() splits the string at the last occurrence of the argument string and
returns a tuple containing the part the before separator, argument string and the
part after the separator.
string.rpartition(separator)
rpartition() Parameters()
rpartition() method takes a string parameter separator that separates the string at
the last occurrence of it.
the part before the separator, separator parameter, and the part after the separator if
the separator parameter is found in the string
two empty strings, followed by the string itself if the separator parameter is not
found
print(string.rpartition('is '))
print(string.rpartition('not '))
string = "Python is fun, isn't it"
print(string.rpartition('is'))
Output
A list can be defined as a collection of values or items of different types. The items in
the list are separated with the comma (,) and enclosed with the square brackets [].
IIf we try to print the type of L1, L2 using type() function then it will come out to be a
list.
print(type(L1))
print(type(L2))
Output:
<class 'list'>
<class 'list'>
Characteristics of Lists
The list has the following characteristics:
a = [1,2,"Peter",4.50,"Ricky",5,6]
b = [1,2,5,"Peter",4.50,"Ricky",6]
a ==b
Output:
False
Both lists have consisted of the same elements, but the second list changed the index
position of the 5th element that violates the order of lists. When compare both lists it
returns the false.
Lists maintain the order of the element for the lifetime. That's why it is the ordered
collection of objects.
Output:
True
In the above example, we have created the lists which consist of the employee and
department details and printed the corresponding details. Observe the above code
to understand the concept of the list better.
The index starts from 0 and goes to length - 1. The first element of the list is stored
at the 0th index, the second element of the list is stored at the 1st index, and so on.
We can get the sub-list of the list using the following syntax.
list_varible(start:stop:step)
list = [1,2,3,4,5,6,7]
print(list[0])
print(list[1])
print(list[2])
print(list[3])
# Slicing the elements
print(list[0:6])
# By default the index value is 0 so its starts from the 0th element and go for index -
1.
print(list[:])
print(list[2:5])
print(list[1:6:2])
Output:
1
2
3
4
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[3, 4, 5]
[2, 4, 6]
Unlike other languages, Python provides the flexibility to use the negative indexing
also. The negative indices are counted from the right. The last element (rightmost) of
the list has the index -1; its adjacent left element is present at the index -2 and so on
until the left-most elements are encountered.
Let's have a look at the following example where we will use negative indexing to
access the elements of the list.
list = [1,2,3,4,5]
print(list[-1])
print(list[-3:])
print(list[:-1])
print(list[-3:-1])
Output:
5
[3, 4, 5]
[1, 2, 3, 4]
[3, 4]
As we discussed above, we can get an element by using negative indexing. In the
above code, the first print statement returned the rightmost element of the list. The
second print statement returned the sub-list, and so on.
Python also provides append() and insert() methods, which can be used to add
values to the list.
Consider the following example to update the values inside the list.
list = [1, 2, 3, 4, 5, 6]
print(list)
# It will assign value to the value to the second index
list[2] = 10
print(list)
# Adding multiple-element
list[1:3] = [89, 78]
print(list)
# It will add value at the end of the list
list[-1] = 25
print(list)
Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]
The list elements can also be deleted by using the del keyword. Python also provides
us the remove() method if we do not know which element is to be deleted from the
list.
Repetition The repetition operator enables the list elements to L1*2 = [1, 2, 3, 4, 1,
2, 3, 4]
be repeated multiple times.
Iteration The for loop is used to iterate over the list for i in l1:
print(i)
elements.
Output
1
2
3
4
Iterating a List
A list can be iterated by using a for - in loop. A simple list containing four strings,
which can be iterated as follows.
Output:
John
David
James
Jonathan
Consider the following example in which, we are taking the elements of the list from
the user and printing the list on the console.
Output:
Example -
list = [0,1,2,3,4]
print("printing original list: ");
for i in list:
print(i,end=" ")
list.remove(2)
print("\nprinting the list after the removal of first element...")
for i in list:
print(i,end=" ")
Output:
manipulated for your analysis. This collection of data is named a list object.
While all methods are functions in Python, not all functions are methods. There’s a
key difference between functions and methods in Python. Functions take objects as
1)sort() method:
The sort() method is a built-in Python method that, by default, sorts the list in
ascending order. However, you’ll modify the order from ascending to descending by
Example
Let’s say you would like to sort the elements of the product’s prices in ascending
order. You’d type prices followed by a . (period) followed by the method name, i.e.,
sort including the parentheses.
2)type() function
For the type() function, it returns the class type of an object.
Example
In this example, we will see the data type of the formed container.
list
3)append() method
The append() method will add some elements you enter to the end of the elements
you specified.
Example
In this example, let’s increase the length of the string by adding the element “April”
to the list. Therefore, the append() function will increase the length of the list by 1.
months = ['January', 'February', 'March']
months.append('April')
print(months)
Output:
4)extend() method
The extend() method increases the length of the list by the number of elements that
are provided to the strategy, so if you’d prefer to add multiple elements to the
Example
In this example, we extend our initial list having three objects to a list having six
objects.
list = [1, 2, 3]
list.extend([4, 5, 6])
list
Output:
[1, 2, 3, 4, 5, 6]
5)index() method
The index() method returns the primary appearance of the required value.
Example
In the below example, let’s examine the index of February within the list of months.
6)max() function
The max() function will return the highest value from the inputted values.
Example
In this example, we’ll look to use the max() function to hunt out the foremost price
within the list named price.
589.36
7)min() function
The min() function will return the rock bottom value from the inputted values.
Example
In this example, you will find the month with the tiniest consumer indicator (CPI).
To identify the month with the tiniest consumer index, you initially apply the min()
function on prices to identify the min_price. Next, you’ll use the index method to
look out the index location of the min_price. Using this indexed location on months,
you’ll identify the month with the smallest consumer indicator.
February
8)len() function
Example
In the below example, we are going to take a look at the length of the 2 lists using
this function.
list_1 = [50.29]
list_2 = [76.14, 89.64, 167.28]
print('list_1 length is ', len(list_1))
print('list_2 length is ', len(list_2))
Output:
list_1 length is 1
list_2 length is 3
9)clear() function
The clear() method removes all the elements from a specified list and converts them
to an empty list.
Example
In this example, we’ll remove all the elements from the month’s list and make the list
empty.
Output:
[]
10)insert() function
The insert() method inserts the required value at the desired position.
Example
In this example, we’ll Insert the fruit “pineapple” at the third position of the fruit list.
Output:
The count() method returns the number of elements with the desired value.
Example
In this example, we are going to return the number of times the fruit “cherry”
3
12)pop() function
The pop() method removes the element at the required position.
Example
In this example, we are going to remove the element that’s on the third location of
the fruit list.
The remove() method removes the first occurrence of the element with the
specified value.
Example
In this example, we will Remove the “banana” element from the list of fruits.
Output:
Example
In this example, we will be reverse the order of the fruit list, so that the first element
in the initial list becomes last and vice-versa in the new list.
Output:
Example
In this example, we want to create a list having the same elements as the list of fruits.
For the cmp() function, it takes two values and compares them against one another.
It will then return a negative, zero, or positive value based on what was inputted.
Example
In the example below, we have two stock prices, and we will compare the integer
stock_price_1 = [50.23]
stock_price_2 = [75.14]
print(cmp(stock_price_1, stock_price_2))
print(cmp(stock_price_1, stock_price_1))
print(cmp(stock_price_2, stock_price_1))
When you run the above code, it produces the following result:
-1
The results show that the stock_price_2 list is larger than the stock_price_1 list. You
can use the cmp() function on any type of list, such as strings. Note that by default, if
The list() function takes an iterable construct and turns it into a list.
Syntax
list([iterable])
Example
In the below example, you will be working with stock price data. Let's print out an
empty list, convert a tuple into a list, and finally, print a list as a list.
# empty list
print(list())
print(list(stocks))
print(list(stocks_1))
When you run the above code, it produces the following result:
[]
Let’s see all the methods one by one with the help of an example.
1)append() method
The append() method will add some elements you enter to the end of the elements
you specified.
Example
In this example, let’s increase the length of the string by adding the element “April”
to the list. Therefore, the append() function will increase the length of the list by 1.
2)extend() method
The extend() method increases the length of the list by the number of elements that
are provided to the strategy, so if you’d prefer to add multiple elements to the
Example
In this example, we extend our initial list having three objects to a list having six
objects.
list = [1, 2, 3]
list.extend([4, 5, 6])
list
Output:
[1, 2, 3, 4, 5, 6]
3)index() method
The index() method returns the primary appearance of the required value.
Example
In the below example, let’s examine the index of February within the list of months.
months = ['January', 'February', 'March', 'April', 'May']
months.index('March')
Output:
4)insert() function
The insert() method inserts the required value at the desired position.
Example
In this example, we’ll Insert the fruit “pineapple” at the third position of the fruit list.
Output:
5)count() function
The count() method returns the number of elements with the desired value.
Example
In this example, we are going to return the number of times the fruit “cherry”
3
6)pop() function
The pop() method removes the element at the required position.
Example
In this example, we are going to remove the element that’s on the third location of
Output:
7)remove() function
The remove() method removes the first occurrence of the element with the
specified value.
Example
In this example, we will Remove the “banana” element from the list of fruits.
Output:
8)copy() function
The copy() method returns a copy of the specified list and makes the new list.
Example
In this example, we want to create a list having the same elements as the list of fruits.
Example
In this example, we will be reverse the order of the fruit list, so that the first element
in the initial list becomes last and vice-versa in the new list.
Output:
10)clear() function
The clear() method removes all the elements from a specified list and converts them
to an empty list.
Example
In this example, we’ll remove all the elements from the month’s list and make the list
empty.
Output:
[]
11)sort() method:
The sort() method is a built-in Python method that, by default, sorts the list in
ascending order. However, you’ll modify the order from ascending to descending by
Example
Let’s say you would like to sort the elements of the product’s prices in ascending
order. You’d type prices followed by a . (period) followed by the method name, i.e.,
sort including the parentheses.
1 cmp(list1, It compares the elements of This method is not used in the Python 3 and the
list2) both the lists. above versions.
Example: 1- Write the program to remove the duplicate element of the list.
list1 = [1,2,2,3,55,98,65,65,13,29]
# Declare an empty list that will store unique values
list2 = []
for i in list1:
if i not in list2:
list2.append(i)
print(list2)
Output:
list1 = [3,4,5,9,10,12,24]
sum = 0
for i in list1:
sum = sum+i
print("The sum is:",sum)
Output:
Example: 3- Write the program to find the lists consist of at least one common
element.
list1 = [1,2,3,4,5,6]
list2 = [7,8,9,2,10]
for x in list1:
for y in list2:
if x == y:
print("The common element is:",x)
Output: