Unit v Data Structures Lists, Sets, Tuples, Dictionaries
Unit v Data Structures Lists, Sets, Tuples, Dictionaries
Unit v Data Structures Lists, Sets, Tuples, Dictionaries
if(flag==0):
print("Not found")
arr = [2,4,6,1,12,46,22,5]
x = 62
search(arr,x)
Sorting
arr = [3,5,12,34,78,23,87,23,0]
arr1 = ['aa','rr','gg','as']
print(sorted(arr))
print(sorted(arr1))
• Selection sort:
Selection Sort is one of the simplest sorting algorithms. It
selects the current smallest element, and swaps it into
place.
• Bubble Sort:
It works by repeatedly swapping the adjacent elements if
they are in the wrong order.
Tuples
Tuples
• Tuple items are ordered, unchangeable, and
allow duplicate values.
• Tuples are written with round brackets.
• E.g
thistuple = ("apple", "banana", "cherry")
print(thistuple)
O/P:
("apple", "banana", "cherry")
Create Tuple With One Item
• To create a tuple with only one item, you
have to add a comma after the item,
otherwise Python will not recognize it as a
tuple.
thistuple = ("apple",)
print(type(thistuple))
thistuple = ("apple")
print(type(thistuple))
O/P:
Operations on
Tuples
Operation Expression Output
Length len(8,3,6,2) 4
Concatenation (5,2,6) + (2,7,1) (5,2,6,2,7,1)
Repetition ("Hi ") * 3 "Hi Hi Hi"
Membership 9 in (5,2,6,2,7,1) False
Comparison tup1 = (4,6,1,2)
(use <, >, ==) tup2 = (4,6,1,2)
print(tup1<tup2) False
Maximum max(4,6,1,2) 6
Minimum min(4,6,1,2) 1
Tuple as return
value
Tuple as return value
• It is preferable to use tuple, in order to return multiple values
from a function.
• Program to return max and min value from a function.
def max_min(vals):
x = max(vals)
y = min(vals)
return (x, y)
vals = (34, 45, 99, 67, 12, 5, 24)
(max_val, min_val) = max_min(vals)
print("The maximum value is: ", max_val,\
", and the minimum value is: ", min_val)
Sets-creating sets
Sets
• A set is a collection which is unordered, unchangeable*,
and unindexed.
• Sets do not allow duplicate values.
• Once a set is created, you cannot change its items, but
you can remove items and add new items.
• The values True and 1 are considered the same value in
sets, and are treated as duplicates
• You cannot access items in a set by referring to an index
or a key.
thisset = {"apple", "banana", "cherry"}
print(thisset)
O/P:
Set operations
1. Add Items
• To add one item to a set use the add() method.
• E.g.
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
O/P
????
2. Add Sets
• To add items from another set into the current set, use the
update() method.
• update() method does not have to be a set, it can be any
iterable object
• E.g.
thisset.update(tropical)
print(thisset)
O/P
????
3. Remove Item
• To remove an item in a set, use the remove(), or the
discard() method.
• E.g.
thisset.remove("banana")
print(thisset)
O/P
????
Note: If the item to remove does not exist, remove() will
raise an error.
thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)
Note: If the item to remove does not exist, discard() will
NOT raise an error.
• pop() - Remove a random item
• clear() - Empties the set
• del - Delete the set completely
Method Description
difference() Returns a set containing the difference between
two or more sets
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.difference(y)
print(z)
O/P:
{'banana', 'cherry'}
intersection() Returns a set, that is the intersection of two
other sets
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.intersection(y)
print(z)
O/P:
{'apple'}
Method Description
isdisjoint() Returns whether two sets have a intersection or
not
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "facebook"}
z = x.isdisjoint(y)
print(z)
O/P:
True
issubset() Returns whether another set contains this set or
not
x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b", "a"}
z = x.issubset(y)
print(z)
O/P:
True
Method Description
issuperset() Returns whether this set contains another set or
not
symmetric_differe Returns a set with the symmetric differences of
nce two sets
()
symmetric_differe inserts the symmetric differences from this set
nce_update() and another
union() Return a set containing the union of sets
update() Update the set with the union of this set and
others
https://www.w3schools.com/python/
python_sets_methods.asp
Dictionaries-operations
and methods
Dictionaries
• Dictionaries are used to store data values in key:value pairs.
• A dictionary is a collection which is ordered*, changeable and do
not allow duplicates.
• E.g
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
O/P:
{'brand': 'Ford', 'model': 'Mustang', 'year':
1964}
Accessing Items
• You can access the items of a dictionary by referring to its key
name, inside square brackets:
E.g
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
print(x)
O/P:
Mustang
Get Keys
• The keys() method will return a list of all the keys in the dictionary.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.keys()
print(x)
O/P:
dict_keys(['brand', 'model', 'year'])
Get Values
• The values() method will return a list of all the values in
the dictionary.
• E.g.
#refer previous example for variable declaration.
x = thisdict.values()
print(x)
O/P:
dict_values(['Ford', 'Mustang', 1964])
Get items
• The items() method will return each item in a dictionary,
as tuples in a list.
• E.g
x = thisdict.items()
print(x)
O/P:
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year',
1964)])
Change Values
• change the value of a specific item by referring to its key
name
• E.g
thisdict["year"] = 2018
print(thisdict)
O/P:
{'brand': 'Ford', 'model': 'Mustang', 'year': 2018}
Adding Items
• Adding an item to the dictionary is done by using a new index key
and assigning a value to it:
• E.g
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
O/P:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
Removing Items
• The pop() method removes the item with the specified
key name:
• E.g
thisdict = { "brand": "Ford", "model": "Mustang",
"year": 1964 }
thisdict.pop("model")
print(thisdict)
O/P
{'brand': 'Ford', 'year': 1964}
• The del keyword removes the item with the specified key name:
• E.g
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
O/P
{'brand': 'Ford', 'year': 1964}
• The del keyword can also delete the dictionary completely:
• E.g
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict)
O/P:
Nameerror
Loop Through a Dictionary
• Print all key names in the dictionary, one by one:
• E.g
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(x)
O/P
brand
Model
year
• Print all values in the dictionary, one by one:
E.G
for x in thisdict:
print(thisdict[x])
O/P
Ford
Mustang
1964
• Loop through both keys and values, by using the items()
method:
• E.g
for x, y in thisdict.items():
print(x, y)
O/P:
brand Ford
model Mustang
year 1964
Aliasing vs Copying
• Aliasing means creating a reference to the particular value with another
name.
E.G
>>> animals
['dog', 'cat', 'pig']
>>> animals_alias = animals #animals is aliased to animals_alias
>>> animals_alias
['dog', 'cat', 'pig’]
>>> animals.append("cow")
>>> animals
['dog', 'cat', 'pig', 'cow']
>>> animals_alias
['dog', 'cat', 'pig', 'cow']
• Copying means creating a exact duplicate copy of a
variable. It does not affect the values of a new variable.
E.G
a=["maths","phy","sci","pyt"]
b=a[:] #content of a is copied to b.
a.append("che")
print(a)
['maths', 'phy', 'sci', 'pyt', 'che']
print(b)
['maths', 'phy', 'sci', 'pyt']
Nested Dictionaries
Nested Dictionaries
• A dictionary can contain dictionaries, this is called nested
dictionaries.
• E.g
myfamily = { "child1" : { "name" : "Emil", "year" : 2004 },
"child2" : { "name" : "Tobias", "year" : 2007 },
"child3" : { "name" : "Linus", "year" : 2011 }
}
print(myfamily)
O/P
{'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name': 'Tobias', 'year':
2007}, 'child3': {'name': 'Linus', 'year': 2011}}
Access Items in Nested
Dictionaries
• To access items from a nested dictionary, you use the
name of the dictionaries, starting with the outer
dictionary:
• E.g
print(myfamily["child2"]["name"])
O/P:
Tobias