0% found this document useful (0 votes)
32 views34 pages

UNIT 3 (Part 1) Data Structures

Uploaded by

mohanqwe903
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views34 pages

UNIT 3 (Part 1) Data Structures

Uploaded by

mohanqwe903
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

UNIT-3

Python
Data Structures
Syllabus
List and List Operations
Using Lists to represent Matrices
Strings, String operations,
Tuples
Dictionaries
Sets
Iterators and generators
comprehensions.
Lists:
Ø List is a data structure and is a collection of ordered & Mutable(changeable)
elements.
Ø List allows duplicate members.
Ø A list is created by placing all the items (elements) inside a square bracket [], separated
by commas.
Ø List is dynamic. They grow and shrink on demand.
Ø It can have elements of same or different data types #List of integers
a=[1,2,3]
a=[] a=[1,2,3] print(a)
print(a) print(a)
print(*a) #List with mixed datatypes
a=[1,”hai”,3.4]
print(a)
Basic List operations
2.Repetition:
1.concatenation:
Syntax: list*int-value
Syntax: listname1+listname2
l=[1,2,3]
l1=[1,2,3] print(l*3)
l2=[4,5,6]
print(l1+l2) o/p:[1,2,3,1,2,3,1,2,3]
o/p:[1,2,3,4,5,6]

3.List Length: l=[10,20,30]


Syntax: len(list) print(len(l))
4. Index: 6. Membership Operator

Syntax: listname[index ] a=[1,2,3]


print(1 in a)
l=(1,2,3,4,5) print(4 not in a)
print(l[1])
print(l[3])

5.Iteration:
Syntax: for i in list:

for i in [1,2,3]:
print(i)
7.slicing: -7 -6 -5 -4 -3 -2 -1
t = [‘a’,’b’,’c’,’d’,’e’,’f’,’g’] t = [‘a’,’b’,’c’,’d’,’e’,’f’,’g’]
print(t) 0 1 2 3 4 5 6
print(t[1])
print(t[1:3]) ['a', 'b', 'c', 'd', 'e', 'f', 'g']
b
print(t[1:-1]) ['b', 'c']
print(t[:3]) ['b', 'c', 'd', 'e', 'f']
['a', 'b', 'c']
print(t[2:]) ['c', 'd', 'e', 'f', 'g']
print(t[:-1]) ['a', 'b', 'c', 'd', 'e', 'f']
['b', 'd', 'f']
print(t[1::2]) ['g', 'f', 'e', 'd', 'c', 'b', 'a']
print(t[::-1])
List:
list methods:
1.append()
2.insert()
3.sort()
4.count()
5.index()
6.pop()
7.remove()
8.reverse()
9.extend()
10.copy()
1.append():

adds a element to the end of the list.


syntax: listname.append(element)
l1=[‘a’,’b’,’c’]
l=[2,4,6,10] l1.append(‘d’)
l.append(12) print(“updated list=”,l1)
print(“updated list=”,l)
#output:[‘a’,’b’,’c’,’d’]
#output:[2,4,6,10,12]
2.insert():
3.sort():
insert one element at a desired location
syntax: listname.sort()
syntax: listname.insert(index,element)
l=[2,3,4,5,1]
l=[1,3,5] l.sort()
l.insert(1,7) print(l)
print(“updated list=”,l)
o/p:[1,2,3,4,5]
#output:[1,7,3,5]
4.count(): 5.index():
syntax: list.count(x)
Syntax:
listname.index(element)
l=[1,2,3,3,4,5]
print(l.count(3)) l=[1,2,3,4,7,10,13,11,12]
print(l.index(13)
o/p:2
o/p: 6
6.pop(): 7.remove():
Syntax: list.pop(element) removes the first instance of
l=[12,14,13,10] element in list.
print(l.pop())
print(l) Syntax: list.remove(element)

o/p:[12,14,13] l=[1,3,5,7,8,3]
l.remove(3)
l=[12,14,13,10] print(l)
print(l.pop(1))
print(l) o/p:[1,5,7,8,3]
o/p:[12,13,10]
8.reverse(): 9.extend():

Syntax: list.reverse() Syntax:list1.extend(list2)


l=[1,4,7,8,11,23]
l1=[2,3,4]
l.reverse()
l2=[‘a’,’b’,’c’]
print(l)
l1.extend(l2)
print(l1)
o/p:[23,11,8,7,4,1]
print(l2)
10.copy(): l1=[3,17,19,2,13]
Syntax: listname.copy() l2=l1.copy()
print(l2)
Tuples:

it is a sequence of immutable objects.

Tuples are fixed in length, heterogeneous, and can be nested.

They are represented by () t2=(1,2,3,4,5)


print(t2)
t1=()
print(type(t1)) t3=(1,1.2,’abc’)
print(t3)
Basic tuple operations
2.Repetition:
1.concatenation:
Syntax: tuple*int-value
Syntax: tuplename1+tuplename2
t=(1,2,3)
t1=(1,2,3) print(t*3)
t2=(4,5,6)
print(t1+t2) o/p:(1,2,3,1,2,3,1,2,3)
o/p:(1,2,3,4,5,6)
t=(10,20,30)
3.Tuple Length:
print(len(t))
Syntax: len(tuple)
4. Index: 5.Membership Operator

Syntax: tuplename[index ] a=(1,2,3)


print(1 in a)
t=(1,2,3,4,5) print(4 not in a)
print(t[1])
print(t[3])
5.Iteration:

Syntax: for i in tuple:

for i in (1,2,3):
print(i)
7.slicing: -7 -6 -5 -4 -3 -2 -1
t = (‘a’,’b’,’c’,’d’,’e’,’f’,’g’) t = (‘a’,’b’,’c’,’d’,’e’,’f’,’g’)
print(t) 0 1 2 3 4 5 6
print(t[1])
print(t[1:3])
print(t[1:-1])
print(t[:3])
print(t[2:])
print(t[:-1])
print(t[1::2])
print(t[::-1])
Methods:
Tuple does not support remove(),pop(),append(),sort(),reverse(),insert()
,extend()
2) count():
1) index():
syntax:
Syntax: tuplename.index(element) tuplename.count(element)
t=(1,2,3,4,7,10,13,11,12) t=(1,2,3,3,4,5)
print(t.index(13)) print(t.count(3))
3)copy: 4)zip():

t1=(1,2,3) t1=(1,2,3)
t2=t1 t2=(5,7,8,9,10)
print(t2) t3=tuple(zip(t1,t2))
print(t3)
l1=[1,2,3]
l2=[5,7,8,9,10]
l3=list(zip(l1,l2))
print(t3)
Sets:
set is unordered collection of elements and it is mutable
Every element is unique and must be immutable(Numbers,Strings,tuples)

Sets are represented by { } or by built in function set()

s={1,2,3} s1={“python”,(1,2,3)} s2={[1,2,3],1.0,’hai’}


print(s) print(s1) print(s2)
s={3,2,3,1} #output:error because list is
print(s) mutable,but set should have immutable
elements
Output:{1,2,3}
Set operations:
2)Intersection(&): 3)Difference(-):
1)Union(|):
a={1,2,3,4,5} a={1,2,3,4,5}
a={1,2,3,4,5} b={4,5,6,7,8}
b={4,5,6,7,8} print(a-b)
b={4,5,6,7,8}
print(a&b)
print(a|b)

4)Set Symmetric difference(^):other 5)Membership operators:


than common elements A={‘a’,1,2.5,3}
a={1,2,3,4,5} print(‘a’in A)
b={4,5,6,7,8} print(1 not in A)
print(a^b)
Set Methods: 2)clear(): 3)copy():

1)add(): Syntax: setname.clear() Syntax:


setname.copy()
Syntax: v={1,2,3,4}
setname.add(element) s={1,2,3}
v.clear()
print(v) s1=s.copy()
s={‘c’,’java’,’cpp’}
s.add(‘python’) print(s1)
print(s) 5)intersection()
a={1,2,3,4,5}
Syntax:
4)difference(): b={4,5,6,7,8}
set1.intersection(set2)
Syntax: print(a.difference(b))
set1.difference(set2) a={1,2,3,4,5}
b={4,5,6,7,8}
print(a.intersection(b))
6)union(): 7)symmetric_difference(): 8)discard():
Syntax:
set1.union(set2) Syntax: Syntax:
set1.symmetric_difference(set2) setname.discard(element)
a={1,2,3,4,5}
a={1,2,3,4,5}
b={4,5,6,7,8} n={1,2,3,4}
b={4,5,6,7,8}
print(a.union(b)) n.discard(3)
print(a. symmetric_difference (b))
print(n)
9)remove():
n={1,2,3,4}
Syntax: n.remove(3)
setname.remove(element) print(n)
n={1,2} 11)isdisjoint():
n.remove(3)
Two sets are said to be disjoint,if they have no common
O/P:#keyerror
elements(True/False)

12)issubset(): Syntax: set1.isdisjoint(set2)


Syntax: a={1,2,3}
set1.issubset(set2) b={4,5,6}
print(a.isdisjoint(b))
a={1,2,3}
b={1,2,3,4}
print(a.issubset(b))
Dictionaries:

Python dictionary is an unordered collection of elements and it is mutable


We can store values as a pair of keys and values

Represented by dict() or {}
Keys in dictionary are unique and they are immutable(strings,numbers,tuples)

d={} d1={1:’A’,2:’J’,3:’P’} d2={‘a’:1,’b’:2,’c’:3}


print(d) print(d2)
print(d1)
print(type(d))

d3={1:1.1,2:’a’,3:[1,2,3],4:(1,2,3)} #mixed dictoinary


print(d3)
d4={[1,2,3]:1,’a’:2} d=dict([(‘a’,1),(‘b’,2),(‘c’,3)])
print(d4) print(d)
#Error-keys are of 3)Iteration:
immutable nature 2)Len:
Iteration is used to access
Syntax: the elements.
Dictionary Operations:
len(dictname) Syntax:
1)index
d={‘a’:1,’b’:2,’c’:3} for i in dictname:
Syntax:
print(len(d)) s={1:1,3:9,5:25,7:49}
dictname[index/key]
Output: for i in s:
d={‘a’:1,’b’:2,’c’:3} 1
9 print(s[i])
print(d[b])
25
49
4)Membership operator: Dictionary Methods 2)values():
s={1:1,3:9,5:25,7:49}
1)keys(): Syntax:
print(1 in s)
Syntax: dictname.keys() dictname.values()
print(48 not in s)
d2={‘a’:1,’b’:2,’c’:3} d2={‘a’:1,’b’:2,’c’:3}
print(d2.keys())
print(d2.values())
3)get():
d2={‘a’:1,’b’:2,’c’:3} 4)update():
Syntax: olddict.update(newdict)
print(d2.get(‘a’)) d={1:’o’,2:’t’,3:’th’}
d1={2:’tw’}
d.update(d1)
print(d)
5)copy():
6)clear():
Syntax: dictname.copy()
Syntax: dictname.clear()
d2={‘a’:1,’b’:2,’c’:3}
d1=d2.copy() d={1:’one’,2:’two’}
print(d2) d.clear()
print(d)

7)pop():
Syntax: dictname.pop(key)
f={1:’app’,2:’man’,3:’stra’}
f.pop(1)
print(f)
#output: {2:’man’,3:’stra’}
Strings
Multiline Strings:
Strings are immutable
a=””” python is
Invented by
Van Rossum”””
print(a)
String Operations: Repetition:
Index:
s1=’python’
Concatenation: a=’Hello python’
print(s1*3)
s1=’python’ print(a[9])
s2=’program’ print(a[-5])
s = ‘abcdefg’
print(s1+s2)
print(s)
Slicing: print(s[-1])
print(s[1:3])
print(s[1:-1])
print(s[:3])
print(s[2:])
print(s[:-1])
print(s[1::2])
print(s[::-1])
Len:
Membership
s=’string’ Iteration:
print(len(s))
s=’python’
s=’python’
print(‘y’ in s)
for i in s: print(‘a’ in s)
print(i) print(‘b’ not in s)
Methods:

1)Capitalize 2)find():if not found returns -1


Syn: Stringname.capitalize() stringname.find(‘substring’)
stringname.find(‘substring’,index)
s=’program’ stringname.find(‘substring’,start,end)
print(s.capitalize())
s=’python programming’
print(s.find(‘pro’))
print(s.find(‘pro’,3))
print(s.find(‘pro’,5,13))
3)rstrip,lstrip,strip()
s=’ hai ‘ 4)index()
print(s.rstrip()) syn:stringname.index(character/substring)
print(s.lstrip())
s=’python programming’
print(s.strip()) print(s.index(‘h’))
print(s.index(‘hon’))
5)count() print(s.index(‘m’))
Syn: stringname.count(substring)
6)replace:
s=’python is awesome’ Syn:stringnmae.replace(‘oldstring’,’new string’)
print(s.count(‘e’))
print(s.count(“es”)) s=’python program’
print(s.count(‘e’,10,15)) print(s.replace(‘p’,’abc’))
7) lower(),upper(): 8) isdigit():
Syn: stringname.lower() Syn:stringname.isdigit()
stringname.upper()
s=’python’ s=’1234’
print(s.upper()) print(s.isdigit())
s=’PROGRAM’ s=’a123’
print(s.lower()) print(s.isdigit())

9)islower() ,isupper() 10)startswith().endswith()


Syn: stringname.islower() Syn:stringname.startswith()
stringname.isupper() stringname.endswith()
s=’python’ s=’python is very interesting’
print(s.islower()) print(s.startswith(‘py’))
print(s.isupper()) print(s.endswith(‘in’))
Comprehensions

2 1
[1,4,9,16…...100]
s=[x*x for x in range(1,11)]
print(s)
Range: 1 to 10

1 in range(T) then 1*1=1


10 in range(T) then 10*10=100
11 in range(F) then stop

[4, 16, 36, 64, 100]


s=[x*x for x in range(1,11) if x%2==0]
Set Comprehensions

x = {i**2 for i in range(10)}

print(x)

Dict Comprehensions

x = {i:i**2 for i in range(10)}

print(x)

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

You might also like