UNIT-4
LIST, TUPLES, DICTIONARIES
Lists
• An ordered group of sequences/Elements
• Separated by symbol(,)
• Enclosed inside square brackets[]
• mutable
Accessing list values
LIST OPERATIONS and inbuilt-function
• extend()
t1=[‘a’ , ‘b’ , ‘c’]
t2=[‘d’, ‘e’]
t1.extend(t2)
print(t1)
Output:[‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
• pop()
• clear()
• index()
• copy()
List loop
• Syntax:
for <list-item> in <list>
statement to process <list_item>
Example:
List=[12, ‘cyber’, 89.9]
for i in list:
print(i)
Output:
12
Cyber
89.9
Using loop with range
a = [1, 3, 5, 7, 9]
n = len(a)
for i in range(n):
print(a[i])
Output
1
3
5
7
9
Using while loop
a = [1, 3, 5, 7, 9]
i = 0
while i < len(a):
print(a[i])
i += 1
Output
1
3
5
7
9
Mutability(changeable)
>>>Number=[10,20,40]
>>>Number[2]=30
>>>print(Number)
10,20,30
Aliasing
• 2 or more variable refers to same object
>>>a=[1,2,3]
>>>b=a
>>>print(“a value=“,a)
>>>print(“b value=“,b)
>>>b.append(‘E’)
>>>print(“after aliasing”)
>>>print(“a value=“,a)
>>>print(“b value=“,b)
Aliasing
Output
a value=[1,2,3]
b value=[1,2,3]
after aliasing
a value=[1,2,3,E]
b value=[1,2,3,E]
Cloning list
• Make copy of list itself, not just the reference
• Slice operator is used for cloning
>>>a=[1,2,3]
>>>b=a[:]
>>>print(“a value=“,a)
>>>print(“b value=“,b)
>>>b.append(‘E’)
>>>print(“after cloning”)
>>>print(“a value=“,a)
>>>print(“b value=“,b)
cloning
Output
a value=[1,2,3]
b value=[1,2,3]
after cloning
a value=[1,2,3]
b value=[1,2,3,E]
List Parameters
• Passing list as argument
def delete_header(t):
del [0]
letters=[‘a’, ‘b’, ‘c’]
delete_header(letters)
print(letters)
Output:
[‘b’ , ‘c]
TUPLE- finite, static, immutable sequence of values
TUPLE VALUES:any data type
Enclosed within ( ): ex t=(5,’a,25.5)
• Creating tuple
– Create with single
element
>>>t=‘a’
• Built-in function
>>>t=tuple()
• Sequence
>>> t=tuple(‘hai’)
>>>print(t)
(‘h’,’a’,’i’)
Operations on tuple
>>>t=(‘h’ ,’a’, ‘i’)
>>>t[0]
‘h’
>>>t[2]
‘i’
>>> t[1:2] #Slice
(‘a’, ‘i’)
>>>t[0]=‘A’
#error(immutable)
>>>t(‘A’)+t[1:]
>>>t
(‘A’, ‘a’, ‘i’)
Tuple illustration
• Tuple assignment
>>>t1=(10,20)
>>>t2=(30,40)
t1,t2=t2,t1
Print(t1) 30,40
Print(t2)10,20
No.of value on left and
right must be equal
t1,t2=t2,t1,t3 #error
t3,t2,t1=t2,t1,t3
• T=()
print(T)
• T=((1,2,3),’hello’,56.7, [8,4,6]) -mixed datatype
print(T)
• T=(‘p’,’y’,’t’,’h’,’o’,’n’)
print(T[3])h
Print(T[1:4])(’y’,’t’,’h’)
Print(T[:])(‘p’,’y’,’t’,’h’,’o’,’n’)
Print(T[4:])(’o’,’n’)
print(T[-1])n
print(T[-4])t
• T1=(“mouse”,[8,6,4],(1,2,3))
print(T1[0][3]) -s
print(T1[1][1])6
Tuples with return value
def circleinfo(r):
c=2*3.14*r
a=3.14*r*r
return (c,a)
r=int(input(“Enter the radius”))
print(circleinfo(r))
Dictionaries(mappings)
• Data structure-immutable
• Values are stored as {key:value} pair
Syntax:
• dic_name={key1:value1,key2:value2}
Hashing:
key value converts into index value
used for accessing values in specific
location
Creation of dictionaries
Method1: creating empty dictionary using {}
A = {}
print("Empty Dictionary: ")
print(A)
Method 2:using literal notation(key value pair)
A = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("nDictionary with the use of key-value: ")
print(A)
Method 3:using dict()
Dict = dict([(1, 'Geeks'), (2, 'For')])
print("nDictionary using dict(): ")
print(Dict)
Adding items into dictionary
>>>cyber={}
>>>print (cyber)
{}
>>>cyber[‘name’]=‘priya’
>>>cyber[‘age’]=18
>>>print(cyber)
{‘name’:’priya’, ‘age’:18}
Accessing items from dictionary
>>>cyber={‘name’:’Priya’, ‘age’:19}
>>>print(cyber[‘name’])
Priya
>>>print(cyber.get(‘age’))
19
Printing dictionary
>>> cyber={‘name’:’Priya’, ‘age’:19}
>>>for x in cyber:
print(x, “:” ,cyber[x])
Output:
name:Priya
age:19
Operation and Methods in Dictionary
• dict()
• dict(s)
• len(d)
• d[key]=value
• del d[key]
• key in d
• values(),keys(),sorted()
Advanced List Processing
PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT-4

PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT-4

  • 1.
  • 2.
    Lists • An orderedgroup of sequences/Elements • Separated by symbol(,) • Enclosed inside square brackets[] • mutable
  • 4.
  • 6.
    LIST OPERATIONS andinbuilt-function • extend() t1=[‘a’ , ‘b’ , ‘c’] t2=[‘d’, ‘e’] t1.extend(t2) print(t1) Output:[‘a’, ‘b’, ‘c’, ‘d’, ‘e’] • pop() • clear() • index() • copy()
  • 8.
    List loop • Syntax: for<list-item> in <list> statement to process <list_item> Example: List=[12, ‘cyber’, 89.9] for i in list: print(i) Output: 12 Cyber 89.9
  • 9.
    Using loop withrange a = [1, 3, 5, 7, 9] n = len(a) for i in range(n): print(a[i]) Output 1 3 5 7 9
  • 10.
    Using while loop a= [1, 3, 5, 7, 9] i = 0 while i < len(a): print(a[i]) i += 1 Output 1 3 5 7 9
  • 11.
  • 12.
    Aliasing • 2 ormore variable refers to same object >>>a=[1,2,3] >>>b=a >>>print(“a value=“,a) >>>print(“b value=“,b) >>>b.append(‘E’) >>>print(“after aliasing”) >>>print(“a value=“,a) >>>print(“b value=“,b)
  • 13.
    Aliasing Output a value=[1,2,3] b value=[1,2,3] afteraliasing a value=[1,2,3,E] b value=[1,2,3,E]
  • 14.
    Cloning list • Makecopy of list itself, not just the reference • Slice operator is used for cloning >>>a=[1,2,3] >>>b=a[:] >>>print(“a value=“,a) >>>print(“b value=“,b) >>>b.append(‘E’) >>>print(“after cloning”) >>>print(“a value=“,a) >>>print(“b value=“,b)
  • 15.
    cloning Output a value=[1,2,3] b value=[1,2,3] aftercloning a value=[1,2,3] b value=[1,2,3,E]
  • 16.
    List Parameters • Passinglist as argument def delete_header(t): del [0] letters=[‘a’, ‘b’, ‘c’] delete_header(letters) print(letters) Output: [‘b’ , ‘c]
  • 17.
    TUPLE- finite, static,immutable sequence of values TUPLE VALUES:any data type Enclosed within ( ): ex t=(5,’a,25.5) • Creating tuple – Create with single element >>>t=‘a’ • Built-in function >>>t=tuple() • Sequence >>> t=tuple(‘hai’) >>>print(t) (‘h’,’a’,’i’) Operations on tuple >>>t=(‘h’ ,’a’, ‘i’) >>>t[0] ‘h’ >>>t[2] ‘i’ >>> t[1:2] #Slice (‘a’, ‘i’) >>>t[0]=‘A’ #error(immutable) >>>t(‘A’)+t[1:] >>>t (‘A’, ‘a’, ‘i’)
  • 18.
    Tuple illustration • Tupleassignment >>>t1=(10,20) >>>t2=(30,40) t1,t2=t2,t1 Print(t1) 30,40 Print(t2)10,20 No.of value on left and right must be equal t1,t2=t2,t1,t3 #error t3,t2,t1=t2,t1,t3 • T=() print(T) • T=((1,2,3),’hello’,56.7, [8,4,6]) -mixed datatype print(T) • T=(‘p’,’y’,’t’,’h’,’o’,’n’) print(T[3])h Print(T[1:4])(’y’,’t’,’h’) Print(T[:])(‘p’,’y’,’t’,’h’,’o’,’n’) Print(T[4:])(’o’,’n’) print(T[-1])n print(T[-4])t • T1=(“mouse”,[8,6,4],(1,2,3)) print(T1[0][3]) -s print(T1[1][1])6
  • 19.
    Tuples with returnvalue def circleinfo(r): c=2*3.14*r a=3.14*r*r return (c,a) r=int(input(“Enter the radius”)) print(circleinfo(r))
  • 20.
    Dictionaries(mappings) • Data structure-immutable •Values are stored as {key:value} pair Syntax: • dic_name={key1:value1,key2:value2} Hashing: key value converts into index value used for accessing values in specific location
  • 21.
    Creation of dictionaries Method1:creating empty dictionary using {} A = {} print("Empty Dictionary: ") print(A) Method 2:using literal notation(key value pair) A = {1: 'Geeks', 2: 'For', 3: 'Geeks'} print("nDictionary with the use of key-value: ") print(A) Method 3:using dict() Dict = dict([(1, 'Geeks'), (2, 'For')]) print("nDictionary using dict(): ") print(Dict)
  • 22.
    Adding items intodictionary >>>cyber={} >>>print (cyber) {} >>>cyber[‘name’]=‘priya’ >>>cyber[‘age’]=18 >>>print(cyber) {‘name’:’priya’, ‘age’:18}
  • 23.
    Accessing items fromdictionary >>>cyber={‘name’:’Priya’, ‘age’:19} >>>print(cyber[‘name’]) Priya >>>print(cyber.get(‘age’)) 19
  • 24.
    Printing dictionary >>> cyber={‘name’:’Priya’,‘age’:19} >>>for x in cyber: print(x, “:” ,cyber[x]) Output: name:Priya age:19
  • 25.
    Operation and Methodsin Dictionary • dict() • dict(s) • len(d) • d[key]=value • del d[key] • key in d • values(),keys(),sorted()
  • 26.