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

UNIT_IV_notes_Python

4 python

Uploaded by

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

UNIT_IV_notes_Python

4 python

Uploaded by

PPTV
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

CK COLLEGE OF ENGINEERING & TECHNOLOGY

Approved by AICTE, New Delhi, Affiliated to


Anna University.
Accredited by NAAC with ‘B’ Grade, An ISO 9001:2015
Certified institute
Jayaram Nagar, Chellangkuppam, Cuddalore

CLASS – I YEAR (I SEM)


SUBJECT CODE: GE3151 (R-2021)
SUBJECT NAME: PROBLEM SOLVING AND PYTHON PROGRAMMING

UNIT IV LISTS, TUPLES, DICTIONARIES

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.

LIST
 A list is a versatile data type contains items separated by commas and enclosed within
square brackets ([ ]). An item can be of any type.
 Each and every item has its unique index.
 A list contains different data type such as string, integer, float, real and another list.
Example:

list=[2345,’bala’,70.8,'A’]
empty = [ ] #empty list
Nested list
A list within another list nested.
n=[‘saran’,’kalai’,[20,45,36]]
List Operations
1. Concatenation
2. Repetition
3. Membership operator
4. List Slice
(i) The + operator concatenates list.
EX:
a = [1, 2, 3]
b = [4, 5, 6]
c=a+b
print(c )

1
O/P:
[1, 2, 3, 4, 5, 6]

(ii) The * operator repeats a list a given number of times.


EX:
print([0] * 4)
[0, 0, 0, 0]
print[1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
(iii) Membership Operator (in and not in)
EX:
fruits=['banana','orange','grapes','apple']
print('orange' in fruits)
print('papaya' in fruits)
print('grapes' not in fruits) #inverse operation

O/P:
==================RESTART:C:/Users/RAMPRIYA/Desktop/sa.py==============
True
False
False

(iv)List Slices (Selection of elements from a list)

List indexing
 Positions are numbered from left to right starting at 0 and it is called as positive
indexing. Positions can also be numbered from right to left starting at -1 and it is called as
negative indexing.

0 1 2 3 4 5
P Y T H O N
-6 -5 -4 -3 -2 -1

Example
my_list = ['p','r','o','b','e']
print(my_list[0])
print(my_list[2])
print(my_list[4])
n_list = ['Happy',[2,0,1,5]]
print(n_list[0][1])
print(n_list[1][3])
my_list = ['p','r','o','b','e']
print(my_list[-1])
print(my_list[-5])

2
Output:
p
o
e
a
5
e
p

List Methods:

Methods that are available with list object in Python programming are tabulated below. They
are accessed as list. Method (). Some of the methods have already been used above.

Python List Methods

append() - Add an element to the end of the list

extend() - Add all elements of a list to the another list

insert() - Insert an item at the defined index

remove() - Removes an item from the list

pop() - Removes and returns an element at the given index

clear() - Removes all items from the list

index() - Returns the index of the first matched item

count() - Returns the count of number of items passed as an argument

sort() - Sort items in a list in ascending order

reverse() - Reverse the order of items in the list

copy() - Returns a shallow copy of the list


Example:
list1=[1,2,3,4]
list1.append(99)
print(list1)
list1.insert(1,100)
print(list1)
list1.remove(4)

3
print(list1)
list1.extend([10,20,30])
print(list1)
list2=[5,2,10,4]
list2.sort()
print(list2)
list2.reverse()
print(list2)
print(list2.index(2))
print(list2.pop(0))
del list2[2]
print(list2)
print(list2.count(4))
print(list2.clear())

Output:
[1, 2, 3, 4, 99]
[1, 100, 2, 3, 4, 99]
[1, 100, 2, 3, 99]
[1, 100, 2, 3, 99, 10, 20, 30]
[2, 4, 5, 10]
[10, 5, 4, 2]
3
10
[5, 4]
1
None

LIST LOOP (TRAVERSING A LIST)


 Traverse the elements of a list is with for loop.
 This loop traverses the list of elements and update each element.
EX:
fruits=['banana','orange','grapes','apple']
for fruit in fruits:
print(fruit)
Output:
banana
orange
grapes
apple

Infinite loop

4
A loop becomes infinite loop if a condition becomes FALSE. Such a loop is called as
infinite loop.
Example: client-server programming (server needs to run continuously so that client can
communicate with it)
Example:
i=1
while i==True:
print('Loop')
Output:
Loop
Loop
Loop
…..
…..
…..
LIST MUTABILITY:
 Lists are mutable because the elements of the list can be altered or assigned.
Example:
numbers=[17,123]
numbers[0]=5
print(numbers)
Output:
[5, 123]
List aliasing
 When two identifiers refer to the same variable or value, then it is called as aliasing.
 This type of change is known as side effect. The variable one and two both refers to the
exact same list object. They are aliases for the same object.
Example.py
one=[10,20,30]
two=one
print(one)
print(two)
one[2]=55
print(one)
print(two)
Output:
[10, 20, 30]
[10, 20, 30]
[10, 20, 55]
[10, 20, 55]
List Cloning
 It is a process of making a copy of the list without modifying the original list.
 When changes are done, it is applied only in duplicate copy and not reflected to original

copy.
Example:

5
original=[20,45,12,36]
duplicate=original.copy()
duplicate[2]='rose'
print(original)
print(duplicate)
Output:
[20, 45, 12, 36]
[20, 45, 'rose', 36]

List Parameters
 A list can also be passed as a parameter to a function.
 If changes are done, then it is notified to main program.
 The list arguments are always passed by reference only.
Program:
def delete(list1):
del list1[3]
return list1
list1=[20,30,12,56,23,100]
print('List Argument:',delete(list1))
Output:
List Argument: [20, 30, 12, 23, 100]

Advanced List Processing:


 List comprehension is used to construct lists in an easy and natural way.
 It creates a list with a subset of elements from another list by applying condition.
 The list comprehension makes code simpler and efficient.
 The execution is much faster than for loop.
Program:
x=[i for i in range(10)]
print(x)
x1=[i for i in range(10) if i%2==0]
print(x1)
x2=[i*2 for i in range(10)]
print(x2)
vowels=('a','e','i','o','u')
w="hello"
x3=[ch for ch in w if ch in vowels]
print(x3)
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 2, 4, 6, 8]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
['e', 'o']

6
TUPLES
 A tuple consists of number of values separated by commas and enclosed within
parentheses.
 Tuples are similar to lists.
 Tuples are immutable sequences. The elements in the tuple cannot be modified.
 The difference between tuple and lists are the tuple cannot be modified like lists and
tuples use parentheses, whereas list use square brackets.
Program:
#Tuple Creation
t1=(23,56,12,20,67,'rose','grapes')
t2='r','g','j','s','f'
empty=()
single=(22,)#Single element tuple
nested=(67,89,t1,t2)#nested tuple
print(t1)
print(t2)
print(empty)
print(single)
print(nested)
Output:
(23, 56, 12, 20, 67, 'rose', 'grapes')
('r', 'g', 'j', 's', 'f')
()
(22,)
(67, 89, (23, 56, 12, 20, 67, 'rose', 'grapes'), ('r', 'g', 'j', 's', 'f'))

Tuple Packing & Unpacking:


t1=(3,'aaa')
a,b=t1
print(a)
print(b)
Output:
3
aaa
#Access tuple elements
t1=(23,56,12,20,67,'rose','grapes')
t2='r','g','j','s','f'
nested=(67,89,t1,t2)
print(t1[6])
print(nested[3][4])
Ouput:
grapes
f

TUPLE OPERATIONS
Concatenation (+) – -> Combine two tuples
t1=('a','b','c')

7
t2=('d','e','f')
print(t1+t2)
Output:
('a', 'b', 'c', 'd', 'e', 'f')
Repeat (*) -  Repeat tuples given number of times.
t1=('c','d')
Output
('c', 'd', 'c', 'd', 'c', 'd')
Membership Operator (in)
t=('a','c','f','g','h','x')
print('c' in t)
Ouput:
True
Inverse(not in)
print('z' not in t)
Output:
True
Python Tuple Methods
my_tuple = ('a','p','p','l','e')
print(my_tuple.count('p'))
print (my_tuple.index('l'))
Output:
2
3
Built-in Functions with Tuple
len()
Return the length (the number of items) in the tuple.
max()
Return the largest item in the tuple.
min()
Return the smallest item in the tuple
sorted()
Take elements in the tuple and return a new sorted list (does not sort the tuple itself).
sum()
Retrun the sum of all elements in the tuple.
tuple()
Convert an iterable (list, string, set, dictionary) to a tuple.
Program
t=(4,6,1,3,9,5,8)
print(len(t))
print(max(t))
print(min(t))
print(sorted(t))
print(sum(t))
print(tuple('welcome'))

8
Output:
7
9
1
[1, 3, 4, 5, 6, 8, 9]
36
('w', 'e', 'l', 'c', 'o', 'm', 'e')
DICTIONARY:
 It is a collection of pair or elements.
 Each pair contains key & value.
 Key and value are separated using : symbol.
 Each pair is separated using , symbol.
 The whole dictionary is enclosed using {}.
 Keys are immutable & values are mutable.
Ex:
d1={1:'fruit',2:'vegetables',3:'cereals'}
print(d1)
o/p:
{1: 'fruit', 2: 'vegetables', 3: 'cereals'}
OPERATIONS:
1. Create - Creating a new dictionary
2. Delete - Removing an element
3. Update –Adding a new element
4. Accessing – Displaying the elements
Program
a={}
a[1]='red'
a[2]='blue'
a[3]='green'
a[4]='grey'
print("Creating a new dictionary")
print(a)
del a[3]
print("After deletion")
print(a)
print("Accessing elements")
print(a[2])
print("Updating Dictionary")
a[1]='orange'
print(a)
Output
Creating a new dictionary
{1: 'red', 2: 'blue', 3: 'green', 4: 'grey'}
After deletion
{1: 'red', 2: 'blue', 4: 'grey'}
Accessing elements
blue
Updating Dictionary

9
{1: 'orange', 2: 'blue', 4: 'grey'}

Dictionary Methods:

S.No Method Syntax Description


Name
1. Clear dict.clear() Removes all elements in dictionary
Returns a shallow copy(alias) of the
2. Copy dict.copy()
dictionary
3. Items dict.items() Returns a list of(key,value) tuple pairs
4. Keys dict.keys() Returns a list of dictionary keys
5. Pop Dict.pop(key[,default]) Remove element with key K and return its
value. Returns default id K is not found.
Removes and return element(key,value)
6. Popitem dict.popitem()
from the last

Program:
h1={1:'APPLE',2:'GRAPES',3:'GUAVA'}
temp=h1.copy()
print("copy()=",temp)
print("items()=",h1.items())
print("keys()=",h1.keys())
print("pop()=",h1.pop(1))
print("popitem()=",h1.popitem())
h1.clear()
print("clear()=",h1)
Output:
copy()= {1: 'APPLE', 2: 'GRAPES', 3: 'GUAVA'}
items()= dict_items([(1, 'APPLE'), (2, 'GRAPES'), (3, 'GUAVA')])
keys()= dict_keys([1, 2, 3])
pop()= APPLE
popitem()= (3, 'GUAVA')
clear()= {}
Illustrative Problems:

10

You might also like