COLLECTION DATA TYPES
I. Sequence Types
Tuple (immutable)
List (mutable)
II. Set (mutable, immutable)
III. Dictionary
Collection types supports
- Membership operator (in)
- Size function (len())
- Slices ( [] )
- Is iterable
TUPLE
- Ordered sequence of 0 or more object reference
- Extract items using slicing
- immutable
Constructor
(a) empty tuple (b) Convert ( c) b = 1,2,3
given object to c = tuple
tuple (b)
>>> a = tuple()
print(c)
>>> print(a) b = ‘hello’ Output -
c = tuple(b) (1,2,3)
Output - ()
print(c)
Output -
(‘h’,’e’,’l’,’l’,’o’)
t = “apple”, 90.5, “green”, 20, “10-09-2020”
t[0] t[1] t[2] t[3] t[4]
appl 90. gree 10-09-
20
e 5 n 2020
t[-5] t[-4] t[-3] t[-2] t[-1]
>>> - 1 ; if not found returns 0
t.count(‘apple’) - 3 ; if not found raise
>>> t.index(20) ValueError
exception
>>> hair = “Black”, “Brown”, “Blonde”,
“Red” ‘Blonde’
>>> hair[2]
(‘Brown’,
>>>hair [-3:] ‘Blonde’ ,’Red’)
((‘Black’, ‘Brown’), ’Grey’,
>>> hair[:2] , “Grey”,
(‘Blonde’, ’Red’))
hair[2:]
Error : Cannot
>>> hair[:2] + “Grey” +
concatenate String to
hair[2:]
Tuple
>>> hair[:2] + (“Grey”,) (‘Black’, ‘Brown’,
+ hair[2:] ’Grey’, ‘Blonde’,
’Red’)
>>> hair = “Black”, “Brown”, “Blonde”, “Red”
>>> eyes = “Brown”, “Hazel”, “Amber”, “Green”,
“Blue”, “Grey”
>>> colors = (hair, eyes) # Nesting of tuples
>>> colors [1] [3:-1] (‘Green’, ‘Blue’)
>>> colors [0] [:-2] (‘Black’, ‘Brown’)
>>> colors [0][1][1:-1]
(‘row’)
MANUFACTURE, MODEL, SEATING = (0, 1, 2)
MIN, MAX = (0, 1) # Unpacking
aircraft = (“Airbus”, “A120-ac”, (100,200))
>>> aircraft[SEATING][MAX] 200
def f(x) :
return x, x**2
>>f (2) (2, 4)
t = ((1,1), (2,4), 11
(3,9)) 24
for x,y in t: 39
print(x,y)
a, b = ( 5, 10)
a, b = b, a
print(a, b) 10 5
NAMED TUPLE
- Using namedtuple() method in collections module
import collections
sale = collections.namedtuple(“Samsung”, “pid custid
date qty price”)
name of custom tuple data type name of each item
tuple takes
>>> S1 = Samsung(
sale( 432, 921, custid
pid=432, “10-09-2020”,
= 921, date2= ,‘10-09-2020’,
2500) qty
>>> S1 = 2, price = 2500 )
>>> total = 0
>>> total = S1.qty * S1.price Total = 5000.00
>>> print (“Total = {0:.2f}”.format(total))
import collections
aircraft = collections.namedtuple(“Indigo”,”
manufacturer model seating”)
seat = collections.namedtuple(“capacity”,”min
max”)
A1 = aircraft(“AirBus”, “A320-ac”, seat(100,200))
Indigo ( manufacturer=‘AirBus’, model=
>>> A1 ‘A320-ac’, seating = capacity(min=100,
max=200) )
200
>>>A1.seating.max
LISTS
- Mutable - replace or delete any items
Constructor
(a) l = list()
>>> l []
(b) l = list (‘APPLE’)[ ‘A’, ‘P’, ‘P’, ‘L’, ‘E’]
>>> l
(c ) list = [-16, “blue”, 100, [1,2,3] ]
[-16, ‘blue’, 100,
>>> list [1,2,3] ]
list [0] -16
list [1][0] ‘b’
list [3][1:] [ 2, 3 ]
>>>list = [1,2,3,4,5]
>>> list.append(1) [1,2,3,4,5,1]
>>> list.count(1) 2
>>> x = [6,7,8]
list.extend(x) ~ list +=[1,2,3,4,5,1,6,7,
x
8]
>>> list.index (1) 0
>>> list.index(1, 3,6)5; if not found raises
start ValueError
end
>>>list = [1,2,3,4,5,6]
>>> list.insert (0,-1) [-1,1,2,3,4,5,6]
>>> list.pop() 6
>>> list.pop(3) 3
index position
>>> list.remove(2) [-1,1,4,5]
item
>>> list.reverse() [5,4,1,-1]
>>> list.sort() [-1,1,4,5]
L = [“ball”, “apple”, “Axe”, “Mirror”, “Bag”]
>>> L.sort() [‘Axe’, ‘Bag’, ‘Mirror’, ‘apple’,
‘ball’]
>>> L.sort(key = str.lower)
[‘apple’, ‘Axe’, ‘Bag’, ‘ball’,
‘Mirror
Sequence Unpacking Operator
>>> first, *rest = [1,2,3,4]
>>> first, rest (1 , [2,3,4] )
>>> *dirc, name = “/usr/bin/file1”.split(“/”)
>>> dirc, name ([‘ ’,‘usr’,’bin’],
‘file1’)
Create a named tuple for type ‘
dress’
(a)Including members pid, name, size,
color, rate
(b)Create rate as named tuple with
members price, rating, comment
>>> import collections
>>> dress = collections.namedtuple("CAPRI",
"pid name size color rate")
>>> D1 = dress(101, "baby", 'S', 'Pink',
568.75)
>>> D1.name
'baby‘
>>> D1.rate
568.75
>>> import collections
>>> dress = collections.namedtuple("CAPRI", "pid name
size color rate")
>>> rate = collections.namedtuple("RATING", "price
rating comment")
>>> D2 = dress(102, "Women", 'XL', 'Beige' ,
rate(1750.50, 5, "Best fit"))
>>> D2.size
'XL'
>>> D2.rate.price
1750.5
>>> D2.rate.rating
5
>>> import collections
>>> dress = collections.namedtuple("CAPRI", "pid name
size color rate")
>>> rate = collections.namedtuple("RATING", "price
rating comment")
>>> price = collections.namedtuple("PRICE","piece
bulk")
>>> D3 = dress(103, "Kid", 'XS', 'Blue', rate(price(250,
225.5), 4.5, "Nice material"))
>>> D3.rate.price.bulk
225.5
List Comprehensions
for i in range(5):
print(i)
Eg:
leaps = []
for year in range(1900,2000):
if(year%4==0):
leaps.append(year)
Syntax (List Comprehension)
[ <expression> for <item> in <iterable> <if
condition >]
>>> leaps = [ year for year in range(1900,2000)
if year%4==0 ]
Square of numbers:
list = [1,2,3,4,5,6]
result = []
for x in list:
if (x%2==0):
result.append(x*x)
>>> result
[4, 16, 36]
result = [x*x for x in list if (x%2==0) ]
Option 1:
a = input(‘Enter numbers : ‘)
b = a.split()
b = [int(i) for i in b]
max(b)
Option 2:
a = input(‘Enter numbers :
‘)
b = a.split()
b = list(map(int, b))
SET
- unordered collection of 0 or more object references
- mutable (set)
- immutable (frozenset)
- When iterated set type provide their items in any arbitrary
order
- No notion of index numbers, hence cannot be sliced
- Empty set created using set() and not using {}
{‘i’, ‘c’, ‘p’, ‘a’, ‘e’,
set(“pecan”) | set(“pie”) - union ‘n’}
{‘p’, ‘e’}
set(“pecan”) & set(“pie”) - intersection
{‘n’, ‘c’, ‘a’}
set(“pecan”) - set(“pie”) - difference
{‘i’, ‘c’, ‘a’, ‘n’}
set(“pecan”) ^ set(“pie”) - symmetric difference
Set Methods
Given s and t are 2 given sets and x is an item;
s.add(x) # Add x to s if not already present
s.clear() # Removes all items from s
s.union(t) # s|t
s.intersection(t) #s&t
s.difference(t) # s – t
s.pop() # Returns and removes a random item
s.remoxe(x) # Removes x from s; if not found raises
KeyError
s.discard(x) # Removes x from s
s.isdisjoint(t); s.issubset(t); s.issuperset(t) # Returns
True or False
Set Comprehension
Syntax {<expression> for <item> in <iterable>
<if condition >}
W = {"a.html", "b.HTML", "c.doc", "d.jpg", "e.htm",
"f.pdf", "g.docx", "h.bmp"}
Files = { x for x in W if
x.lower().endswith((“.htm”, “.html”))}
{‘e.htm’, ‘b.HTML’,
>> Files ‘a.html’}
DICTIONARY
- unordered collection of 0 or more key-value pairs
- Keys are immutable; but values are mutable
- Keys are unique; if add an item with existing key, value of key
is replaced
- No notion of index positions, hence cannot be sliced
(a)d1 = {“id”:10, “name”:”Bismi”, “score”:90}
(b)d2 = dict ( {“id”:10, “name”:”Bismi”, “score”:90} ) #
dictionary literal
(c)d3 = dict( [(“id”,10), (“name”,”Bismi”), (“score”,90)] ) #
sequence
(d)d4 = dict (id=10, name=”Bismi”, score=90) #
d1 = {“id”:10, “name”:”Bismi”, “score”:90}
# Adding an item
d1 [“course”] = “MCA” {“id”:10, “name”:”Bismi”, “score”:90,
“course”: ‘MCA’}
# Accessing values
>>> d1 [“name”]
>>> d1[“score”]
# Deleting an item
>>> del d1[“score”]
d1.items() # Returns (key, value) as a sequence
d1.keys() # Return keys alone as sequence
d1.values() # Return values as sequence
d = {“id”:10, “name”:”Bismi”, “score”:90}
for item in d.items():
print(item[0], item[1])
for k, v in d.items():
print(k, v)
for item in d.values():
print(item)
for item in d: (~ d.keys())
print(item)
# Counting occurrences of words in a line of text
words = {}
def countwords(line):
for w in line.split():
words[w] = words.get(w,0) + 1
>>>countwords(“India is my country I love my
country”)
>>> words
{‘India’:1, ‘is’:1, ‘my’:2, ‘country’:2, ‘I’:1, ‘love’:1}
Dictionary Comprehension
Syntax
{<key expression>:<value expression> for
key,value in iterable [if condition]}
Eg: To create an inverted dictionary
d = {‘India’:1, ‘is’:1, ‘my’:2, ‘country’:2, ‘I’:1,
‘love’:1}
{1:’love’, 2:’country’}
Invert = {v:k for k,v in d.items()}