Unit3 DataStructures
Unit3 DataStructures
Data Structure:
A data structure is a collection of data elements (such as numbers or characters—or even other
data structures) that is structured in some way, for example, by numbering the elements. The most
basic data structure in Python is the "sequence".
Lists
-> List is one of the Sequence Data structure
-> Lists are collection of items (Strings, integers or even other lists)
List Creation
In [1]: emptyList = []
print(lst4)
List Length
List Append
In [3]: lst = ['one', 'two', 'three', 'four']
print(lst)
List Insert
In [4]: #syntax: lst.insert(x, y)
print(lst)
List Remove
In [5]: #syntax: lst.remove(x)
print(lst)
#append
lst.append(lst2)
print(lst)
lst.extend(lst2)
print(lst)
List Delete
In [8]: #del to remove item based on index position
del lst[1]
print(lst)
print(lst)
print(lst)
if 'two' in lst:
print('AI')
AI
ML
List Reverse
In [11]: #reverse is reverses the entire list
lst.reverse()
print(lst)
List Sorting
The easiest way to sort a List is with the sorted(list) function.
That takes a list and returns a new list with those elements in sorted order.
The sorted() optional argument reverse=True, e.g. sorted(list, reverse=True), makes it sort
backwards.
sorted_lst = sorted(numbers)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-15-f7fe17ce83fb> in <module>
1 lst = [1, 20, 'b', 5, 'a']
----> 2 print(lst.sort()) # can't sort list with element of different datatype
s.
s = "one,two,three,four,five"
slst = s.split(',')
print(slst)
List Indexing
Each item in the list has an assigned index value starting from 0.
2
3
List Slicing
Accessing parts of segments is called slicing.
The key point to remember is that the :end value represents the first value that is not in the
selected slice.
print(new_lst)
List Count
In [29]: numbers = [1, 2, 3, 1, 3, 4, 2, 5]
#frequency of 1 in a list
print(numbers.count(1))
#frequency of 3 in a list
print(numbers.count(3))
2
2
List Looping
In [30]: #loop through a list
one
two
three
four
List Comprehensions
List comprehensions provide a concise way to create lists.
Common applications are to make new lists where each element is the result of some operations
applied to each member of another sequence or iterable, or to create a subsequence of those
elements that satisfy a certain condition.
In [33]: #example
matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
print(transposed)
Tuples
localhost:8888/notebooks/OneDrive/Desktop/python unit 3 MCA IV sem.ipynb# 9/24
3/22/2021 python unit 3 MCA IV sem - Jupyter Notebook
-> The diffence between the two is that we can't change the elements of tuple once it is assigned
whereas in the list, elements can be changed
Tuple creation
In [36]: #empty tuple
t = ()
#nested tuple
t = (1, (2, 3, 4), [1, 'xyz', 28, 'abc'])
print(t)
(1, 2, 3)
(1, 'xyz', 28, 'abc')
(1, (2, 3, 4), [1, 'xyz', 28, 'abc'])
Out[37]: str
Out[38]: tuple
print(t)
<class 'tuple'>
('text',)
print(t[1])
cd
xyz
print(t[1])
In [45]: print(t[1][2])
In [46]: #Slicing
t = (1, 2, 3, 4, 5, 6)
print(t[1:4])
(2, 3, 4)
(1, 2, 3, 4)
(1, 2, 3, 4, 5, 6)
Changing a Tuple
-> unlike lists, tuples are immutable
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-47-1fb87c1270c4> in <module>
2 t = (1, 2, 3, 4, [5, 6, 7])
3
----> 4 t[2] = 'x' #will get TypeError
t = (1, 2, 3) + (4, 5, 6)
print(t)
(1, 2, 3, 4, 5, 6)
In [50]: #repeat the elements in a tuple for a given number of times using the * operator.
t = (('hi', ) * 4)
print(t)
Tuple Deletion
In [51]: #we cannot change the elements in a tuple.
# That also means we cannot delete or remove items from a tuple.
Tuple Count
In [52]: t = (1, 2, 3, 1, 3, 3, 4, 1)
Out[52]: 3
Tuple Index
In [53]: t = (1, 2, 3, 1, 3, 3, 4, 1)
Tuple Memebership
In [54]: #test if an item exists in a tuple or not, using the keyword in.
t = (1, 2, 3, 4, 5, 6)
print(1 in t)
True
In [55]: print(7 in t)
False
Built in Functions
Tuple Length
In [56]: t = (1, 2, 3, 4, 5, 6)
print(len(t))
Tuple Sort
In [57]: t = (4, 5, 1, 2, 3)
new_t = sorted(t)
print(new_t) #Take elements in the tuple and return a new sorted list
#(does not sort the tuple itself).
[1, 2, 3, 4, 5]
print(max(t))
23
Sets
-> A set is an unordered collection of items. Every element is unique (no duplicates).
-> The set itself is mutable. We can add or remove items from it.
-> Sets can be used to perform mathematical set operations like union, intersection, symmetric
difference etc.
Set Creation
In [61]: #set of integers
s = {1, 2, 3}
print(s)
#print type of s
print(type(s))
{1, 2, 3}
<class 'set'>
In [62]: #set doesn't allow duplicates. They store only one instance.
s = {1, 2, 3, 1, 4}
print(s)
{1, 2, 3, 4}
{1, 2, 3}
print(type(s))
<class 'set'>
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-65-22d0618a89be> in <module>
4
5 #set object doesn't support indexing
----> 6 print(s[1]) #will get TypeError
{1, 2, 3}
{1, 2, 3, 5, 6}
{1, 2, 3, 5, 6, 8, 9, 10}
s = {1, 2, 3, 5, 4}
print(s)
print(s)
{1, 2, 3, 4, 5}
{1, 2, 3, 5}
print(s)
{1, 3, 5}
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-71-fcd391652dec> in <module>
1 #remove an element not present in a set s
----> 2 s.remove(7) # will get KeyError
KeyError: 7
{1, 3, 5}
s = {1, 2, 3, 5, 4}
print(s)
{2, 3, 4, 5}
In [74]: s.pop()
print(s)
{3, 4, 5}
In [75]: s = {1, 5, 2, 3, 6}
print(s)
set()
print(set1 | set2)
{1, 2, 3, 4, 5, 6, 7}
{1, 2, 3, 4, 5, 6, 7}
{3, 4, 5}
{3, 4, 5}
In [80]: #set Difference: set of elements that are only in set1 but not in set2
print(set1 - set2)
{1, 2}
{1, 2}
#use ^ operator
print(set1^set2)
{1, 2, 6, 7}
{1, 2, 6, 7}
#check y is subset of x
print("set 'y' is subset of 'x' ?", y.issubset(x))
Frozen Sets
Frozen sets has the characteristics of sets, but we can't be changed once it's assigned. While tuple
are immutable lists, frozen sets are immutable sets
Sets being mutable are unhashable, so they can't be used as dictionary keys. On the other hand,
frozensets are hashable and can be used as keys to a dictionary.
This datatype supports methods like copy(), difference(), intersection(), isdisjoint(), issubset(),
issuperset(), symmetric_difference() and union(). Being immutable it does not have method that
localhost:8888/notebooks/OneDrive/Desktop/python unit 3 MCA IV sem.ipynb# 18/24
3/22/2021 python unit 3 MCA IV sem - Jupyter Notebook
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-85-627ec1ce44a6> in <module>
3
4 #try to add element into set1 gives an error
----> 5 set1.add(5)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-86-5c8e05737e66> in <module>
----> 1 print(set1[1]) # frozen set doesn't support indexing
frozenset({1, 2, 3, 4, 5, 6})
#or
print(set1.intersection(set2))
frozenset({3, 4})
frozenset({3, 4})
#or
print(set1.symmetric_difference(set2))
frozenset({1, 2, 5, 6})
frozenset({1, 2, 5, 6})
Dictionary
localhost:8888/notebooks/OneDrive/Desktop/python unit 3 MCA IV sem.ipynb# 19/24
3/22/2021 python unit 3 MCA IV sem - Jupyter Notebook
Python dictionary is an unordered collection of items. While other compound data types have only
value as an element, a dictionary has a key: value pair.
Dict Creation
In [90]: #empty dictionary
my_dict = {}
my_dict = dict([(1, 'abc'), (2, 'xyz')]) #create a dict with list of tuples
print(my_dict)
Dict Access
In [91]: my_dict = {'name': 'abc', 'age': 27, 'address': 'india'}
#get name
print(my_dict['name'])
abc
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-92-ac4c061783ba> in <module>
1 #if key is not present it gives KeyError
----> 2 print(my_dict['degree'])
KeyError: 'degree'
india
In [94]: #if key is not present it will give None using get method
print(my_dict.get('degree'))
None
#update name
my_dict['name'] = 'xyz'
print(my_dict)
print(my_dict)
print(my_dict)
20
{'name': 'abc', 'address': 'india'}
print(my_dict)
print(squares)
print(squares)
{}
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-101-6fac7747ecad> in <module>
4 del squares
5
----> 6 print(squares) #NameError because dict is deleted
Dictionary Methods
In [102]: squares = {2: 4, 3: 9, 4: 16, 5: 25}
my_dict = squares.copy()
print(my_dict)
In [103]: #fromkeys[seq[, v]] -> Return a new dictionary with keys from seq and value equal
subjects = {}.fromkeys(['Math', 'English', 'Hindi'], 0)
print(subjects)
dict_keys([2, 3, 4, 5])
Dict Comprehension
In [108]: #Dict comprehensions are just like list comprehensions but for dictionaries
('a', 1)
('b', 2)
('c', 3)
In [109]: #Creating a new dictionary with only pairs where the value is larger than 2
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
new_dict = {k:v for k, v in d.items() if v > 2}
print(new_dict)
{'c': 3, 'd': 4}
In [110]: #We can also perform operations on the key value pairs
d = {'a':1,'b':2,'c':3,'d':4,'e':5}
d = {k + 'c':v * 2 for k, v in d.items() if v > 2}
print(d)
In [ ]: