GE3151_UNIT4_PRINT
GE3151_UNIT4_PRINT
Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list
parameters; Tuples: tuple assignment, tuple as return value; Dictionaries: operations and
methods; advanced list processing - list comprehension; Illustrative programs: simple
sorting, histogram, Students marks statement, Retail bill preparation.
LISTS
● List is an ordered sequence of elements. Value`s in the list are called elements / items.
● It can be written as a list of comma-separated elements (values) between square brackets [ ].
● Operations on lists:
1. Create a list
2. Indexing
3. Slicing
4. Concatenation
5. Repetitions
6. Updating
7. Membership
8. Comparison
[Type text]
7. Membership >>> a=[2,3,4,5,6,7,8,9,10] Returns True if element is present in
>>> 5 in a list. Otherwise returns false.
True
>>> 100 in a
False
>>> 2 not in a
False
8 .Comparison >>> a=[2,3,4,5,6,7,8,9,10] Returns True if all elements in both
>>>b=[2,3,4] elements are same. Otherwise returns
>>> a==b false
False
>>> a!=b
True
LIST SLICES
List slicing is an operation that extracts a subset of elements from a list and packages them as
another list.
Syntax:
Listname[start:stop]
Listname[start:stop:steps]
● default start value is 0
● default stop value is n-1
● [:] this will print the entire list
● [2:2] this will create a empty slice
3 LIST METHODS
❖ Methods used in lists are used to manipulate the data quickly.
❖ These methods work only on lists.
❖ They do not work on the other sequence types that are not mutable, that is,
the values they contain cannot be changed, added, or deleted.
[Type text]
Syntax: listname.method name( element/index/list)
[Type text]
15 a.clear() >>> a.clear() Removes all items from the
>>> print(a) list.
[]
16 del(a) >>> del(a) Delete the entire list.
>>> print(a)
Error: name 'a' is not
defined
LIST LOOPS
i. For loop
ii. While loop
iii. Infinite Loop
i) For Loop
❖ The for loop in Python is used to iterate over a sequence (list, tuple, string) or other
iteratable objects.
❖ Iterating over a sequence is called traversal.
❖ Loop continues until we reach the last item in the sequence.
❖ The body of for loop is separated from the rest of the code using indentation.
Syntax: for val in sequence
● The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true.
● When the condition is tested and the result is false, the loop body will be skipped and the
first statement after the while loop will be executed.
Syntax:
while (condition):
body of while
[Type text]
Example:
a=[1,2,3,4,5]
i=0
sum=0
while i<len(a):
sum=sum+a[i]
i=i+1
print(sum) output 15
MUTABILITY
● Lists are mutable. (can be changed)
● Mutability is the ability for certain types of data to be changed without entirely
recreating it.
● An element can be changed in a list by accessing it directly as part of the assignment
statement.
● Using the indexing operator (square brackets[ ]) on the left side of an assignment, one of
the list elements can be updated.
Example description
[Type text]
ALIASING
● Creating a copy of a list is called aliasing. When you create a copy both list will be having
same memory location. Changes in one list will affect another list.
● Aliasing refers to having different names for same list values.
Example Output:
a= [1, 2, 3 ,4 ,5] [1, 2, 3, 4, 5]
b=a True
print (b) [100,2,3,4,5]
a is b [100,2,3,4,5]
a[0]=100
print(a)
print(b)
● In this a single list object is created and modified using the subscript operator.
● When the first element of the list named “a” is replaced, the first element of the list
● named “b” is also replaced.
● This type of change is what is known as a side effect. This happens because
after the assignment b=a, the variables a and b refer to the exact same list
object.
● They are aliases for the same object. This phenomenon is known as aliasing.
● To prevent aliasing, a new object can be created and the contents of the
original can be copied which is called cloning.
CLONING
● To avoid the disadvantages of copying we are using cloning. Creating a copy of
a same list of elements with two different memory locations is called cloning.
● Changes in one list will not affect locations of another list.
● Cloning is a process of making a copy of the list without modifying the original list.
1. Slicing
2. list()method
3. copy() method
[Type text]
LIST AS PARAMETERS
● In python, arguments are passed by reference.
● If any changes are done in the parameter which refers within the function, then the
changes also reflect back in the calling function.
● When a list to a function is passed, the function gets a reference to the list.
● Passing a list as an argument actually passes a reference to the list, not a copy of the list.
● Since lists are mutable, changes made to the elements referenced by the parameter
change the same list that the argument is referencing.
Example Output
def remove(a): [2,3,4,5]
a.remove(1)
a=[1,2,3,4,5]
remove(a)
print(a)
def insert(a): [30, 1, 2, 3, 4, 5]
a.insert(0,30)
a=[1,2,3,4,5]
insert(a)
print(a)
TUPLE
A tuple is same as list, except that the set of elements is enclosed in parentheses instead of
square brackets.
❖ A tuple is an immutable list. i.e. once a tuple has been created, you can't add elements to
a tuple or remove elements from the tuple.
❖ But tuple can be converted into list and list can be converted in to tuple.
methods Example description
list( ) >>> a=(1,2,3,4,5) it convert the given tuple
>>> a=list(a) into list.
>>> print(a)
[1, 2, 3, 4, 5]
tuple( ) >>> a=[1,2,3,4,5] it convert the given list into
>>> a=tuple(a) tuple.
>>> print(a)
(1, 2, 3, 4, 5)
Benefit of Tuple:
❖ Tuples are faster than lists.
❖ If the user wants to protect the data from accidental changes, tuple can be used.
❖ Tuples can be used as keys in dictionaries, while lists can't.
❖ Operations of tuples
1. Creating a tuple
2. Indexing
3. Slicing
4. Concatenation
5. Repetitions
6. Membership
7. Comparison
[Type text]
Operations Examples Description
1. Creating a tuple >>>a=(20,40,60,”apple”,”ball”) Creating the tuple with elements of
Different data types.
2. Indexing >>>print(a[0]) Accessing the item in the position 0
20 Accessing the item in the position 2
>>> a[2]
60
3. Slicing >>>print(a[1:3]) Displaying items from 1st till 2nd
(40,60)
[Type text]
TUPLE ASSIGNMENT
❖ Tuple assignment allows variables on the left of an assignment operator and values of
tuple on the right of the assignment operator.
❖ Multiple assignment works by creating a tuple of expressions from the right hand side,
and a tuple of targets from the left, and then matching each expression to a target.
❖ Because multiple assignments use tuples to work, it is often termed
tuple assignment.
❖ It is often useful to swap the values of two variables.
Example:
Swapping using temporary variable: Swapping using tuple assignment:
a=20 a=20
b=50 b=50
temp = a (a,b)=(b,a)
a=b print("value after swapping is",a,b)
b = temp
print("value after swapping is",a,b)
Multiple assignments: Multiple values can be assigned to multiple variables using tuple
assignment. Example
>>>(a,b,c)=(1,2,3) -packing
>>>print(a) -unpacking
1
>>>print(b)
2
>>>print(c)
3
Example: Output:
def printall(*args): (2, 3, 'a')
print(args)
printall(2,3,'a')
DICTIONARIES
❖ Dictionary is an unordered collection of elements. An element in dictionary has
a key: value pair.
❖ All elements in dictionary are placed inside the curly braces i.e. { }
❖ Elements in Dictionaries are accessed via keys and not by their position.
❖ The values of a dictionary can be any data type.
❖ Keys must be immutable data type (numbers, strings, tuple)
Operations on dictionary
1. Creating a dictionary
2. Accessing an element
3. Update
4. Add element
5. Membership
Operations Example Description
len(a) a={1: 'ONE', 2: 'two', 3: 'three'} It returns the length of the list.
>>>lena(a)
3
clear() a={1: 'ONE', 2: 'two', 3: 'three'} Remove all elements from the
>>>a.clear() dictionary.
>>>print(a)
>>>{ }
del(a) a={1: 'ONE', 2: 'two', 3: 'three'} It will delete the entire
>>> del(a) dictionary.
Difference between List, Tuples and dictionary
Selection sort
● The selection sort selects the smallest element in the list. When the element is found, it is
swapped with the first element in the list
● Then the second smallest element in the list is then searched. When the element is found, it
is swapped with the second element in the list
● This process of selection and exchange continues, until all the element in the list has been
sorted in ascending order.
3. Swap the first number with minimum. After each iteration, minimum is placed in the front of the
unsorted list.
For each iteration, indexing starts from the first unsorted element. Step 1 to 3 are repeated until all
the elements are placed at their correct position
Program:
A = [20,12,10,15,2]
for i in range(len(A)-1):
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
A[i],A[min_idx] = A[min_idx], A[i]
print ("Sorted array")
for i in range(len(A)):
print("%d" %A[i],end=" ")
Output
Sorted array
2 10 12 15 20
Bubble Sort
● Bubble Sort is a simple sorting algorithm. This sorting algorithm repeatedly compares two
adjacent elements and swaps them if they are in the wrong order.
● It is also known as the sinking sort.
● It has a time complexity of O(n2) in the average and worst cases scenarios and O(n) in the
best-case scenario.
● Bubble sort can be visualized as a queue where people arrange themselves by swapping
with each other so that they all can stand in ascending order of their heights.
● Or in other words, we compare two adjacent elements and see if their order is wrong, if the
order is wrong we swap them.
● i.e arr[i] > arr[j] for 1 <= i < j <= s; where s is the size of the array, if array is to be in
ascending order, and vice-versa).
● Here we sort the following sequence using bubble sort
list1 = [2,23,10,1]
print("The unsorted list is: ", list1)
# Calling the bubble sort function
print("The sorted list is: ", bubble_sort(list1))
Output:
The unsorted list is: [2,23,10,1]
The sorted list is: [1,2,10,23]
INSERTION SORT
● Insertion sort is a sorting algorithm that places an unsorted element at its suitable
place in each iterations
● Insertion sort works similarly as we sort cards in our hand in a card game.
● We assume that the first card is already sorted then, we select an unsorted card. If the
unsorted card is greater than the card in hand, it is placed on the right otherwise, to
the left. In the same way, other unsorted cards are taken and put in their right place.
Coding
a = [ 8,5,7,1,9,3 ]
for i in a :
j = a.index ( i )
while j > 0 :
if a[ j -1 ] > a[j] :
a[j-1],a[j]=a[j],a[j-1]
j=j-1
else:
break
print ( a )
Output
[1, 3, 5, 7, 8, 9]
Explanation
3. Students marks statement
Coding
mark=[]
tot=0
students=[]
grade=[]
num1=int(input('Enter no of students'))
for num in range(num1):
x=input('Enter name of students')
students.append(x)
print('Enter marks obtained in 5 subjects')
for i in range(5):
mark.append(input())
for i in range(5):
tot=tot+int(mark[i])
avg=tot/5
print('Name=',x)
if avg>=91 and avg<=100:
print('Grade=A')
elif avg>=71 and avg<91:
print('Grade=B')
elif avg>=50 and avg<71:
print('Grade=C')
else:
print('Result: Fail')
Output:
Enter no of students: 2
Enter name of students: Anand
Enter marks obtained in 5 subjects
98
97
96
91
95
Name=Anand
Grade=A
Enter no of students: 2
Enter name of students: Raj
Enter marks obtained in 5 subjects
20
30
35
25
35
Name=Raj
Result:Fail
4. Retail bill preparation
tax=0.18
rate={'pencil':10, 'pen':20, 'scale':7, 'A4paper':165,'writingpad':10}
print('Retail Bill calculator\n')
print('Enter the quantity of ordered item:\n')
pencil=int(input('Pencil:'))
pen=int(input('Pen:'))
scale=int(input('Scale:'))
A4paper=int(input('A4 Paper:'))
writingpad=int(input('Writing pad:'))
cost=pencil*rate['pencil']+pen*rate['pen']+
scale*rate['scale']+A4paper*rate['A4paper']+writingpad*rate['writingpad']
bill=cost+cost*tax
print('Please pay Rs. %f'%bill)
Output
Retail bill calculator
Enter the quality of ordered item:
Pencil: 5
Pen: 7
Scale: 4
A4paper: 3
Writingpad:2
Please pay Rs. 876.740000