P2S12019Batch Content
P2S12019Batch Content
Problem3: Flowchart for an algorithm which gets two numbers and prints sum of their value.
1.15 Types of control structures:
Definition
The logic of a program may not always be a linear sequence of statements to be executed in that order.
The logic of the program may require execution of a statement based on a decision.
Control structures specify the statements to be executed and the order of execution of statements.
Where is the usage of control structure?
Flowchart and Pseudo Code use Control structures for representation
2. Take input of two numbers from the user and do the division of two numbers?
1.15.2 Selection (Branch or conditional):
It‘s asked a true/false question THEN selects the next instruction based on the answer.
It selects a statement to execute on the basis of condition. Statement is executed when the condition is
true and ignored when it is false
Example: if, if else, switch structures.
Example problem:
3. Draw a flowchart to determine greatest among two numbers?
Iterative Structure
Example problem:
Write an algorithm and flowchart to find Total Sum from 1 to 100 natural numbers
Step 1: Start
Step 2: Read value of n
Step 3: Set i←1
Step 4: Set Total_Sum 0
Step 5: Repeat the steps until i greater than n
a) Set Total_SumTotal_Sum+i
b) increment i // (i.e. i=i+1)
Step 6: Display ―1 to 100 Natural Numbers Sum:‖ Total_Sum
Step 7: End
Example problem:
1. Draw a flowchart to determine largest among three numbers?
Answer: Process Box: A process box is used to represent all types of mathematical tasks like addition,
subtraction, multiplication, division, etc.
9. Algorithm to find area of a rectangle?
Algorithm:
Step 1: Start
Step 2: Take length and breadth and store them as L and B? // Input
Step 4: Multiply L and B and store it in area //Area of Rectangle = L*B
Step 5: Print area //Output
Step 6: Stop.
10. Write an algorithm to find the largest among three different numbers entered by user with flowchart
Step 1: Start
Step 2: Read variables a, b and c.
Step 3: If a greater than b
a) If a greater than c
i) Display a is the largest number.
b) else
i) Display c is the largest number.
Step 4: else
a) If b greater than c
i) Display b is the largest number.
b) else
i) Display c is the greatest number.
Step 5: Stop
Multiple Choice Questions:
1) An Algorithm is expressed by
a) Flowchart b) common language c) pseudo code d) all
2) A good algorithm having finite steps?
a) True b) False
3) Algorithm efficiency is measured by?
a) Speed b) space c) code d) all of the above
4) How many control structures are there in algorithm?
a) 3 b) 2 c) 1
5) Which control structure used weather a condition is true or false?
a) Selection b) iteration c) sequence d) none
6) Which control structure used to check a condition more than one time?
a) Iteration b) loop c) a & b d) None of the above
7) In computer science, algorithm refers to a pictorial representation of a flowchart.
a) True b) False
8) The process of drawing a flowchart for an algorithm is called __________
a) Performance b) Evaluation c) Algorithmic Representation d) Flowcharting
9) Actual instructions in flowcharting are represented in _________
a) Circles b) Boxes c) Arrows d) Lines
10) A box that can represent two different conditions.
a) Rectangle b) Diamond c) Circle d) Parallelogram
11) The following box denotes?
a) Decision b) Initiation c) Initialization d) I/O
12) There should be certain set standards on the amount of details that should be provided in a flowchart
a) True b) False
13) Which of the following is not an advantage of a flowchart?
a) Better communication b) Efficient coding c) Systematic testing d) Improper documentation
14) The symbol denotes _______
Quitting Python
Script Mode
This mode is used to execute Python program written in a file. Such a file is called a script. Scripts can be
saved to disk for future use. Python scripts should have the extension .py, it means that the filename ends
with .py.
For example: helloWorld.py
To execute this file in script mode we simply write python3 helloWorld.py at the command prompt.
If you are running new version of Python, then you need to use print statement with parenthesis as in print ("Hello,
IIIT RK Valley");.However in Python version 2.7, this produces the following result:
We assume that you have Python interpreter set in PATH variable. Now, try to run this program as follows:
$ python3 simple.py
This produces the following result:
We can use the above mentioned functions in python 2.x, but not on python 3.x. input() in python 3.x always return a
string. Moreover, raw_input() has been deleted from python 3
python2.x python3.x
raw_input() -------------- input()
input() ------------------- eval(input())
We can simply say in python 3.x only use of the input () function to read value from the user and it assigns a string to a
variable.
x = input()
The parentheses are empty because, the input function does not require any information to do its job.
Program 3.7 (usinginput.py) demonstrates that the input function produces a string value.
The second line shown in the output is entered by the user, and the program prints the first, third, and fourth lines.
After the program prints the message Please enter some text:, the program‘s execution stops and waits for the user to
type some text using the keyboard. The user can type, backspace to make changes, and type some more. The text the
user types is not committed until the user presses the Enter (or return) key. In Python 3.X, input() function produces
only strings, by using conversion functions we can change the type of the input value. Example as int(), str() and
float().
Exercise
1) What is a programming language?
2) Explain different types of programming languages?
3) What is a compiler?
4) What is an interpreter?
5) How is compiled or interpreted code different from source code?
6) Difference between Interpreter and Compiler?
7) What is Python Programming Language?
8) How many ways can run the Python Programming?
9) What is print statement
10) What is prompt
11) Print ―Welcome to Python Programming Language‖ from interactive Python.
12) Write above statement in exercise1.py to print the same text.
13) Run the modified exercise1.py script.
14) Write the below statements in exercise2.py to print the same below
15) What is a variable?
16) What is value? How can you define the type of value?
17) What is assignment statement?
18) What is comment?
19) What is expression?
20) Write a program that uses raw_input to prompt a user for their Name and then welcomes them.
21) Write a program to prompt the user for hours and rate per hour to compute gross pay.
22) Assume that we execute the following assignment statements: width = 17, height = 12.0
For each of the following expressions, write the value of the expression and the type (of the value of the
expression).
(a) width/2
(b) width/2.0
(c) height/3
(d) 4. 1 + 2 * 5
23) Write program and also Use the Python interpreter to check your answers.
24) Write a program which prompts the user for a Celsius temperature, convert the temperature to Fahrenheit, and
print out the converted temperature.
25) Will the following lines of code print the same thing? Explain why or why not.
x=6
print(6)
print("6")
26) What happens if you attempt to use a variable within a program, and that variable has not been assigned a value?
27) What is wrong with the following statement that attempts to assign the value ten to variable x? 10 = x
28) In Python can you assign more than one variable in a single statement?
29) Classify each of the following as either a legal or illegal Python identifier:
a. Flag h. sumtotal
b. if i. While
c. 2x j. x2
d. -4 k. $16
e. sum_total l. _static
f. sum-total m. wilma‘s
g. sum total
30) What can you do if a variable name you would like to use is the same as a reserved word?
31) What is the difference between the following two strings? ‘n‘ and ‘\n‘?
32) Write a Python program containing exactly one print statement that produces the following output
Output
In while loop there are mainly it contains three parts, which are as follows
Initialization: to set the initial value for the loop counter. The loop counter may be an increment counter or a
decrement counter
Decision: an appropriate test condition to determine whether the loop be executed or not
Updation: incrementing or decrementing the counter value.
Example Programs:
Q1. Write a program to display your name up to „n‟ times
When you run the following program, then output will be display like
Output:
4.1.1 The infinite while loop: A loop becomes infinite loop if a condition never becomes FALSE. You must use
caution when using while loops because of the possibility that this condition never resolves to a FALSE value. This
results in a loop that never ends. Such a loop is called an infinite loop.
An infinite loop might be useful in client/server programming where the server needs to run continuously so that client
programs can communicate with it as and when required.
Program to demonstrate infinite loop:
Above two programs that never stop, that executes until your Keyboard Interrupts (ctrl+c). Otherwise, it would have
gone on unendingly. Many ‗Hi‘ output lines will display when you executes above two programs and that never
display ‗Good bye‘
4.1.2 While loop with else clause/statement: Python allows an optional else clause at the end of a while loop. This is
a unique feature of Python. If the else statement is used with a while loop, the else statement is executed when the
condition becomes false. But, the while loop can be terminated with a break statement. In such cases, the else part is
ignored. Hence, a while loop's else part runs if no break occurs and the condition is False
Syntax:
Example Program:
Q1. Write a program to demonstrate while loop with else block.
Output:
Output:
Module 2 – For Loop
4.2 for loop
Like the while loop, for loop works, to repeat statements until certain condition is True. The for loop in python is used
to iterate over a sequence (list, tuple, string and range() function) or other iterable types. Iterating over a s sequence is
called traversal. Here, by sequence we mean just an ordered collection of items. for loop is usually known as definite
loop because the programmer knows exactly how many times the loop will repeat.
Syntax:
for counter_variable in sequence:
block of statements
Here counter_variable is the variable name that takes the value of the item inside the sequence on each iteration. Loop
continues until we reach the last item in the sequence. The body of for the loop is separated from the rest of the code
using indentation.
Example programs:
Q7. Write a program to make sum of all numbers stored in a list.
Q9. If you want to display including the given input number you can write a program like
Output:
Output:
Here, the for loop prints numbers from the starting number to less than ending number. When the for loop exhausts, it
executes the block of code in the else and prints No items left.
Q. Program to demonstrate else block in for loop with break statement:
Output:
Note:
You can put any type of loop inside of any other type of loop. For example, a for loop can be inside a while loop or
vice versa.
Example Program: Program to demonstrate nested for loop Nested while loop:
Output:
If you run above two programs output will be the same
while loop
Output:
4.4.2Continue Statement: The continue statement is used to skip the rest of the code inside a loop for the current
iteration only. Loop does not terminate but continues on with the next iteration. Continue statement is opposite to
break statement, instead of terminating the loop; it forces to execute the next iteration of the loop.
Syntax:
continue
Flowchart:
Example Programs:
Write a program to demonstrate continue statement by using for loop
Output:
In output, 5 integer value is skipped based on if condition and continues flow of the loop until the condition satisfied.
4.4.3 Pass Statement: The pass statement in Python is used when a statement is required syntactically but you do not
want any command or code to execute. It is a null statement. However, nothing happens when the pass statement is
executed. It results in no operation (NOP). Pass statement can also be used for writing empty loops, functions and
classes.
Syntax:
pass
Example Program:
Program to demonstrate pass statement using for loop
Output:
Solved Questions
1. Write a program to display your name up to n times.
Using while loop
Output:
15) Write a Python program to construct the following patterns, using a nested loop number
1 P
23 PY
456 PYT
7 8 9 10 PYTH
11 12 13 14 15 PYTHO
PYTHON
Multiple Choice Questions:
1) A while loop in Python is used for what type of iteration?
a) Indefinite b) Discriminate c) Definite d) Indeterminate
2) When does the else statement written after loop executes?
a) When break statement is executed in the loop
b) When loop condition becomes false
c) Else statement is always executed
d) None of the above
3) What do we put at the last of for/while loop?
a) Semicolon b) Colon c) Comma d) None of the above
4) Which of the following loop is work on the particular range in python?
a) For loop b) While loop c) Do-while loop d) Recursion
5) How many times it will print the statement?, for i in range(100): print(i)
a) 101 b) 99 c) 100 d) 0
6) What is the result of executing the following code?
We cannot delete or remove characters from string,deleting the string is possible use the keyword del.
Comparing Strings: Python allows you to compare strings using relational (or comparison) operator such as
= =,! =, >, <, < =, >=,etc.
== if two strings are equal, it returns True
!= or <> if two strings are not equal, it returns True
if first string is greater than the second, it returns True
< if second string is greater than the first ,it returns True
>= if first string is greater than or equal to the second, it returns True
<= if second string is greater than or equal to the first, it returns True
Note:
These operators compare the strings by using the lexicographical order i.e using ASCII values of the
characters.
The ASCII values of A-Z is 65 -90 and ASCII code for a-z is 97-122 .
Logical Operators on String in Python: Python considers empty strings as having boolean value of ‗false‘ and non-
empty string as having boolean value of ‗true‘.
Let us consider the two strings namely str1 and str2 and try boolean operators on them:
Output:
Example:
Example:
Example:
Python program to print reverse string using for loop
The functionmax() returns the max character from string str according to ASCII value.in first print statement
y is max character, because ASCII code of "y" is 121. In second print statement "s" is max character, ASCII
code of "s" is 115.
Syntax:- max(str)
The functionmin() returns the min character from string str according to ASCII value.
Syntax :- min(str)
Module – 3
5.7 String Methods
count():The method count() returns the number of occurrence of Python string substr in string str. By using
parameter start and end you can give slice of str.This function takes 3 arguments, substring, beginning
position (by default 0) and end position (by default string length).Return Int Value
Syntax: str.count(substr [, start [, end]])
endswith(“string”, beg, end): This function returns true if the string ends with mentioned string(suffix) else
return false.Return Bool Value
The use of start and end to generate slice of Python string str.
Syntax: str.endswith(suffix[, start[, end]])
startswith(“string”, beg, end):This function returns true if the string begins with mentioned string(prefix)
else return false.
find(“string”, beg, end):This function is used to find the position of the substring within a string. It takes 3
arguments, substring , starting index(by default 0) and ending index(by default string length).
o It returns ―-1‖ if string is not found in given range.
o It returns first occurrence of string if found.
Return the lowest index in S where substring sub is found
If given Python string is found, then the find() method returns its index. If Python string is not found then -1 would be
returned.
Syntax : str.find(str, beg=0 end=len(string))
rfind(“string”, beg, end): This function is similar to find(), but it returns the position of the last occurrence of
sub string.
replace(): This function is used to replace the substring with a new substring in the string. This function has 3
arguments. The string to replace, new string which would replace and max value denoting the limit to replace
action (by default unlimited).
The method isalnum() is used to determine whether the Python string consists of alphanumeric characters,
false otherwise
Syntax :-str.isalnum()
The method isalpha() return true if the Python string contains only alphabetic character(s), false otherwise.
Syntax :- str.isalpha()
The method isdigit() return true if the Python string contains only digit(s),false otherwise.
Syntax :-str.isdigit()
The method islower() return true if the Python string contains only lower cased character(s), false otherwise
Syntax :- str.isdigit()
The method isspace() return true if the Python string contains only white space(s).
Syntax :- str.isspace()
The method istitle() return true if the string is a titlecased
Syntax :- str.istitle()
The method isupper() return true if the string ontains only upper cased character(s), false otherwise.
Sytax:-str.isupper()
The method ljust(), it returns the string left justified. Total length of string is defined in first parameter of
method width. Padding is done as defined in second parameter fillchar .( default is space)
Syntax : -str.ljust(width[, fillchar])
In above example you can see that if you don't define the fillchar then the method ljust() automatically take
space as fillchar.
The method rjust(), it returns the string right justified. Total length of string is defined in first parameter of
methodwidth. Padding is done as defined in second parameter fillchar .( default is space)
Syntax:-str.rjust(width[, fillchar])
This function capitalize() first letter of string.
Syntax:-str.capitalize()
The method lower() returns a copy of the string in which all case-based characters have been converted to
lower case.
Syntax:-str.lower()
The method upper() returns a copy of the string in which all case-based characters have been converted to
upper case.
Syntax:-str.upper()
The method title() returns a copy of the string in which first character of all words of string are capitalised.
Syntax:-str.title()
The method swapcase() returns a copy of the string in which all cased based character swap their case
Syntax:-str.swapcase()
This method join() returns a string which is the concatenation of given sequence and stringas shown in
example.
seq = it contains the sequence of separated strings.
str = it is the string which is used to replace the separator of sequence
Syntax:-str.join(seq)
The method lstrip() returns a copy of the string in which specified char(s) have been stripped from left side
of string. If char is not specified then space is taken as default.
Syntax : - str.lstrip([chars])
The method rstrip() returns a copy of the string in which specified char(s) have been stripped from right side
of string. If char is not specified then space is taken as default.
Syntax : - str.rstrip([chars])
The method strip() returns a copy of the string in which specified char(s) have been stripped from both side
of string. If char is not specified then space is taken as default.
Syntax : - str.strip([chars])
The method split() returns a list of all words in the string, delimiter separates the words. If delimiter is not
specified then whitespace is taken as delimiter, parameter num
Syntax :- str.split("delimiter", num)
Multiple Choice Questions
1) What will be the output of above Python code?
a) 1 b) 6/4 c) 1.5 d) str1
2) Which of the following is False?
a) String is immutable.
b) capitalize() function in string is used to return a string by converting the whole given string into
uppercase.
c) lower() function in string is used to return a string by converting the whole given string into
lowercase.
d) None of these
3) What will be the output of below Python code?
a) format B. formation C. orma D. ormat
4) What will be the output of below Python code?
a) Application b) Application c) ApplicAtion d) Application
a) 70251 b) 7 c) 15 d) Error
7) Which of the following will give "Simon" as output?
3. Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string. If
the string length is less than 2, return instead of the empty string.
Solutions:-
Unsolved Problems
1. Write a program to find number of digits ,alphabets and symbols ?
2. Write a program to convert lower case to upper case from given string?
3. Write a program to print the following output? image like
4. Write a program to check whether given string is palindrome or not?
5. Write a program to find no_ words, no_letters, no_digits and no_blanks in a line?
6. Write a program to sort list names in alphabetical order?
7. To find the first character from given string,count the number of times repeated
and replaced with * except first character then print final string?
8. To find the strings in a list which are matched with first character equals to last character in a string?
9. Write a program that accepts a string from user and redisplays the same string after removing vowels from it?
10. This is a Python Program to take in two strings and display the larger string without using built-in functions?
11. Python Program to Read a List of Words and Return the Length of the Longest One?
12. Python Program to Calculate the Number of Upper-Case Letters and Lower-Case Letters in a String?
Unit 6 - List, Tuples and Dictionary
Module 1 - List
6.1 Definition
Python offers a range of compound data types often referred to as sequences. List is one of the most frequently used
and very versatile data types used in Python. Like a string, a list is a sequence of values. In a string, the values are
characters; in a list, they can be any type. The values in list are called elements or sometimes items.
There are several ways to create a new list; the simplest is to enclose the elements in square brackets and are separated
by commas. It can have any number of items and they may be of different types (integer, float, string etc.).
[10, 20, 30, 40]
['crunchy frog', 'ram bladder', 'lark vomit']
The first example is a list of four integers. The second is a list of three strings. The elements of a list don‘t have to be
the same type. The following list contains a string, a float, an integer, and another list:
['spam', 2.0, 5, [10, 20]]
A list can also have another list as an item. This is called a nested list. It can have any number of items and they may
be of different types (integer, float, string etc.).
6.2 How to create a list?
In Python programming, a list is created by placing all the items (elements) inside square brackets [], separated by
commas.
# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
# list with mixed data types
my_list = [1, "Hello", 3.4]
6.3 How to access elements from a list?
There are various ways in which we can access the elements of a list.
6.3.1 List Index: We can use the index operator [] to access an item in a list. In Python, indices start at 0. So, a list
having 5 elements will have an index from 0 to 4. Trying to access indexes other than these will raise an IndexError.
The index must be an integer. We can't use float or other types, this will result in TypeError.
Nested lists are accessed using nested indexing.
6.3.2 Negative indexing
Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item
and so on.
When we run the above program, we will get the following output:
e
p
6.4 Change or add elements to a list
p
The syntax for accessing the elements of a list is the same as for accessing the characters of a string the bracket
operator. The expression inside the brackets specifies the index. Remember that the indices start at 0:
Unlike strings, lists are mutable because you can change the order of items in a list or reassign an item in a list. When
the bracket operator appears on the left side of an assignment, it identifies the element of the list that will be assigned.
>>> numbers = [17, 123]
>>>numbers[1] = 5
>>> print numbers
[17, 5]
The one-eth element of numbers, which used to be 123, is now 5.
You can think of a list as a relationship between indices and elements. This relationship is called a mapping; each
index ―maps to‖ one of the elements.
List indices work the same way as string indices:
6.5 Traversing a list
The most common way to traverse the elements of a list is with a for loop. The syntax is the same as for strings:
cheeses = ['Cheddar', 'Edam', 'Gouda']
for cheese in cheeses:
print (cheese)
This works well if you only need to read the elements of the list. But if you want to write or update the elements, you
need the indices. A common way to do that is to combine the functions range and len:
numbers = [17, 123]
for i in range(len(numbers)):
numbers[i] = numbers[i] * 2
This loop traverses the list and updates each element.len returns the number of elements in the list. range returns a list
of indices from 0 to n−1, where n is the length of the list. Each time through the loop, i gets the index of the next
element. The assignment statement in the body uses i to read the old value of the element and to assign the new value.
A for loop over an empty list never executes the body:
for x in empty:
print ('This never happens.')
Although a list can contain another list, the nested list still counts as a single element. The length of this list is four:
['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]
6.6 List operations
The + operator concatenates lists:
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print (c)
[1, 2, 3, 4, 5, 6]
Similarly, the * operator repeats a list a given number of times:
>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
The first example repeats [0] four times. The second example repeats the list [1, 2, 3] three times.
List slices: The slice operator also works on lists
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>>t[1:3]
['b', 'c']
>>>t[:4]
['a', 'b', 'c', 'd']
>>>t[3:]
['d', 'e', 'f']
If you omit the first index, the slice starts at the beginning. If you omit the second, the slice goes to the end. So if you
omit both, the slice is a copy of the whole list.
>>>t[:]
['a', 'b', 'c', 'd', 'e', 'f']
Since lists are mutable, it is often useful to make a copy before performing operations that fold, spindle, or mutilate
lists.
A slice operator on the left side of an assignment can update multiple elements:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>>t[1:3] = ['x', 'y']
>>> print (t)
['a', 'x', 'y', 'd', 'e', 'f']
Syntax: List[start:end:step]
start –starting point of the index value end
stop –ending point of the index value
step- increment of the index values
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>>t[1:3:1]
['b', 'c']
6.7 List methods
Adding Elements into a list
6.7.1 list.append()
Python provides methods that operate on lists. For example, append adds a new element to the end of a list
>>> t = ['a', 'b', 'c']
>>>t.append('d')
>>> print (t)
['a', 'b', 'c', 'd']
6.7.2 list.extend()
extend takes a list as an argument and appends all of the elements
>>> t1 = ['a', 'b', 'c']
>>> t2 = ['d', 'e']
>>> t1.extend(t2)
>>> print (t1)
['a', 'b', 'c', 'd', 'e']
This example leaves t2 unmodified.
sort arranges the elements of the list from low to high:
>>> t = ['d', 'c', 'e', 'b', 'a']
>>>t.sort()
>>> print(t)
['a', 'b', 'c', 'd', 'e']
6.7.3 list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert,
so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).
Example 1: Inserting an Element to the List
# vowel list
vowel = ['a', 'e', 'i', 'u']
# 'o' is inserted at index 3
# the position of 'o' will be 4th
vowel.insert(3, 'o')
print('Updated List:', vowel)
Deleting elements
6.7.4 list.remove(x)
Remove the first item from the list whose value is equal to x. It raises a ValueError if there is no such item.
6.7.5 list.clear()
Remove all items from the list. Equivalent to del a[:].
Example 1: Working of clear() method
# Defining a list
list = [{1, 2}, ('a'), ['1.1', '2.2']]
# clearing the list
list.clear()
print('List:', list)
6.7.6 list.pop([i])
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. (The square brackets around the I in the method signature denote that the parameter is optional, not
that you should type square brackets at that position. You will see this notation frequently in the Python Library
Reference.)
>>> t = [„a‟, „b‟, „c‟]
>>> x = t.pop(1)
>>> print (t)
[„a‟, „c‟]
>>> print (x)
b
If you don‘t need the removed value, you can use the del operator:
>>> t = [„a‟, „b‟, „c‟]
>>> del t[1]
>>> print (t)
[„a‟, „c‟]
If you know the element you want to remove (but not the index), you can use remove:
>>> t = [„a‟, „b‟, „c‟]
>>>t.remove(„b‟)
>>> print (t)
[„a‟, „c‟]
The return value from remove is None.
To remove more than one element, you can use del with a slice index:
>>> t = [„a‟, „b‟, „c‟, „d‟, „e‟, „f‟]
>>> del t[1:5]
>>> print (t)
[„a‟, „f‟]
As usual, the slice selects all the elements up to, but not including, the second index.
6.7.6 list.index(x[, start[, end]])
Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such
item.
The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a
particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather
than the start argument.
Example:
# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']
# index of 'e' in vowels
index = vowels.index('e')
print('The index of e:', index)
# element 'i' is searched
# index of the first 'i' is returned
index = vowels.index('i')
print('The index of i:', index)
Example: Working of index() With Start and End Parameters
# alphabets list
alphabets = ['a', 'e', 'i', 'o', 'g', 'l', 'i', 'u']
# index of 'i' in alphabets
index = alphabets.index('e') # 2
print('The index of e:', index)
# 'i' after the 4th index is searched
index = alphabets.index('i', 4) # 6
print('The index of i:', index)
# 'i' between 3rd and 5th index is searched
index = alphabets.index('i', 3, 5) # Error!
print('The index of i:', index)
6.7.7 list.count(x)
Return the number of times x appears in the list.
Example:
# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']
# count element 'i'
count = vowels.count('i')
# print count
print('The count of i is:', count)
# count element 'p'
count = vowels.count('p')
# print count
print('The count of p is:', count)
6.7.8 list.sort(key=None, reverse=False)
Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).
Most list methods are void; they modify the list and return None. If you accidentally write list= list.sort(), you will be
disappointed with the result.
Example : Sort a given list
# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']
# sort the vowels
vowels.sort()
# print vowels
print('Sorted list:', vowels)
Example : Sort the list in Descending order
# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']
# sort the vowels
vowels.sort(reverse=True)
# print vowels
print('Sorted list (in Descending):', vowels)
6.7.9 list.reverse()
Reverse the elements of the list in place.
# Operating System List
systems = ['Windows', 'macOS', 'Linux']
print('Original List:', systems)
# List Reverse
systems.reverse()
# updated list
print('Updated List:', systems)
6.7.10 list.copy()
Return a shallow copy of the list. Equivalent to a[:]
# mixed list
my_list = ['cat', 0, 6.7]
# copying a list
new_list = my_list.copy()
print('Copied List:', new_list)
6.8 List Comprehension
List comprehension is an elegant and concise way to create a new list from an existing list in Python. A list
comprehension consists of an expression followed by for statement inside square brackets. Here is an example to
make a list with each item being increasing power of 2.
List Membership Test:
We can test if an item exists in a list or not, using the keyword in.
Output:
Example:2
Output: 1
Output: 2
Example:3
Output:
Module 2 – Tuples
We saw that lists and strings have many common properties, such as indexing and slicing operations. They are two
examples of sequence data types (Sequence Types — list, tuple, range). Since Python is an evolving language, other
sequence data types may be added. There is also another standard sequence data type: the tuple.
A tuple consists of a number of values separated by commas, for instance:
As you see, on output tuples are always enclosed in parentheses, so that nested tuples are interpreted correctly; they
may be input with or without surrounding parentheses, although often parentheses are necessary anyway (if the tuple
is part of a larger expression). It is not possible to assign to the individual items of a tuple, however it is possible to
create tuples which contain mutable objects, such as lists.
Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples
are immutable, and usually contain a heterogeneous sequence of elements that are accessed via unpacking or indexing
(or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and
are accessed by iterating over the list.
A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to
accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is
constructed by following a value with a comma. For example:
A tuple can also be created without using parentheses. This is known as tuple packing.
Negative Indexing:
Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second last item and so on.
Slicing:
We can access a range of items in a tuple by using the slicing operator colon:.
Slicing can be best visualized by considering the index to be between the elements as shown below. So if we want to
access a range, we need the index that will slice the portion from the tuple.
Deleting a Tuple
As discussed above, we cannot change the elements in a tuple. It means that we cannot delete or remove items from a
tuple. Deleting a tuple entirely, however, is possible using the keyword del.
Output:
Example: 2
Output:
Module3 - Dictionaries
A dictionary is like a list, but more general. In a list, the index positions have to be integers; in a dictionary, the
indices can be (almost) any type.
You can think of a dictionary as a mapping between a set of indices (which are called keys) and a set of values. Each
key map to a value. The association of a key and a value is called a key-value pair or sometimes an item.
As an example, we‘ll build a dictionary that map from English to Spanish words, so the keys and the values are all
strings.
The function dict creates a new dictionary with no items. Because dict is the name of a built-in function, you should
avoid using it as a variable name.
>>> eng2sp = dict()
>>> print (eng2sp)
{}
The curly brackets, {}, represent an empty dictionary. To add items to the dictionary,you can use square brackets:
>>> eng2sp['one'] = 'uno'
This line creates an item that maps from the key ‘one‘ to the value 'uno'. If weprint the dictionary again, we see a key-
value pair with a colon between the keyand value:
>>> print (eng2sp)
{'one': 'uno'}
This output format is also an input format. For example, you can create a newdictionary with three items:
>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
But if you print eng2sp, you might be surprised:
>>> print (eng2sp)
{'one': 'uno', 'three': 'tres', 'two': 'dos'}
The order of the key-value pairs is not the same. In fact, if you type the same example on your computer, you might
get a different result. In general, the order of items in a dictionary is unpredictable.
But that‘s not a problem because the elements of a dictionary are never indexed with integer indices. Instead, you use
the keys to look up the corresponding values:
>>> print (eng2sp['two'])
'dos'
The key ‟two‟ always maps to the value 'dos' so the order of the items doesn‘t matter.
If the key isn‘t in the dictionary, you get an exception:
>>> print (eng2sp['four'])
KeyError: 'four'
6.16 Accessing Elements from Dictionary
While indexing is used with other data types to access values, a dictionary uses keys. Keys can be used either inside
square brackets [] or with the get() method.
If we use the square brackets [], KeyError is raised in case a key is not found in the dictionary. On the other hand,
the get() method returns None if the key is not found.
Output:
6.17 Changing and Adding Dictionary elements
Dictionaries are mutable. We can add new items or change the value of existing items using an assignment operator.
If the key is already present, then the existing value gets updated. In case the key is not present, a new (key: value)
pair is added to the dictionary.
Output:
When looping through a sequence, the position index and corresponding value can be retrieved at the same time using
the enumerate() function.
To loop over two or more sequences at the same time, the entries can be paired with the zip() function.
Example:1
Example:2
Example:3