Unit III Data Structures
Unit III Data Structures
(23DCE2101)
6 list.pop() It deletes and returns last element from the list >>> list1.pop()
9
list.pop(n) It deletes and returns element that is at nth index in the >>> list1.pop(2)
list 3
list.pop(-n) It deletes and returns nth element from the last of the >>> list1.pop(-2)
list 5
7 list.remove(item) It deletes the given item from the list. >>> list1.remove(3)
>>> list1
[1, 5, 8, 5, 9]
If item appears more than once, then item with lower >>> list1.remove(5)
index is removed. >>> list1
[1, 8, 5, 9]
8 list.reverse() It reverses the position (index number) of the items in >>> list1.reverse()
the list [9, 5, 8, 3, 5, 1]
9 list.sort() Sorts items from the list # ascending by default >>> list1.sort()
[1, 3, 5, 5, 8, 9]
10 list.sort(reverse= It sorts the elements inside the list and uses compare list.sort(key=len)
True|False, function if provided
key=myFunc)
list.sort() # list remains unchanged, returns sorted list
sorted(list) # list is sorted in place, original list is sorted
>>> strs = ['aa', 'BB', 'zz', 'CC']
>>> print(sorted(strs)) ## ['BB', 'CC', 'aa', 'zz'] (case sensitive)
>>> print(sorted(strs, reverse=True)) ## ['zz', 'aa', 'CC', 'BB']
>>> strs = ['ccc', 'aaaa', 'd', 'bb']
>>> print(sorted(strs, key=len)) ## ['d', 'bb', 'ccc', 'aaaa']
## "key" argument specifying str.lower function to use for sorting
>>> print(sorted(strs, key=str.lower)) ## ['aa', 'BB', 'CC', 'zz']
+ operator is used to combine lists:
>>> list1 = [10, 20, 30]
>>> list2 = [‘a’, ’b’]
>>> list1+list2
[10, 20, 30, ‘a’, ‘b’]
* operator is used to repeat the list:
>>> list2 * 2
[‘a’, ’b’, ’a’, ‘b]
>>> strs = ['ccc', 'aaaa', 'd', 'bb']
>>> print(sorted(strs, key=len)) ## ['d', 'bb',
'ccc', 'aaaa']
Tuples
• Linear and ordered data structure
• Tuples are unchangeable (immutable)
• Heterogeneous elements
Sr. Immutable (values cannot be modified) Mutable (values can be
No. modified)
Its return type is a sorted list. We can also use it for sorting a list in descending order.
Does not modify the original iterable Modifies the original list in-place
It can only sort a list that contains only one type of value. It sorts the list in-place.
Can handle different types of iterables Limited to lists, raises an error for other types
Can be used with strings for alphabetical sorting Directly applicable to lists of strings
Dictionaries
• Dictionary is a non-linear, unordered data structure used to store
key-value pairs indexed by keys. Keys are unique and keys can be
duplicate. Dictionaries are changeable(mutable). Dictionaries can be
nested.
• Syntax:
<dictionary_name> = {key1:value1, key2:value2,….,keyN:valueN}
Ex. emp = {“ID”:20, “Name”:”Amar”, “Gender”:”Male”, “Salary”:50}
Creating dictionary >>> dict1={}
>>> dict1
{}
>>> dict2 = {1:”Orange”, 2:”Mango”, 3:”Banana”}
>>> dict3 = {“name”:”Vijay”, 1:[10,20]}
creating dictionary using dict() >>> d1 = dict({1:”Orange”, 2:”Mango”, 3:”Banana”})
>>> d1
{1:”Orange”, 2:”Mango”, 3:”Banana”}
>>> d2 = dict([(1, “Red”), (2, “Yellow”), (3, “Green”)])
>>> d2
{1: 'Red', 2: 'Yellow', 3: 'Green'}
>>> d3 = dict(one=1, two=2, three=3)
>>> d3
{'one': 1, 'two': 2, 'three': 3}
Accessing values in a >>> dict3[‘name’]
dictionary: By referring to its ‘Vijay’
key name, inside square >>> d1[1]
brackets ([]) ‘Orange’
>>> d3[‘four’]
Traceback (most recent call last): # key is not in dictionary, so exception
File "<pyshell#12>", line 1, in <module> # This exception can be avoided,
d3['four'] # by using get() method
KeyError: 'four'
Using get() method returns >>> dict1 = {‘name’:’Vijay’, ‘age’:40}
the value for key if key is in >>> dict1.get(‘name’)
dictionary, else None, so that ‘Vijay’
this method never raises a >>> dict1.get(‘adr’)
KeyError # None returned
>>>
Deleting items from >>> squares = {1:1, 2:4, 3:9, 4:16, 5:25}
Dictionary >>> print(squares.popitem()) #remove and return arbitrary item
(5, 25)
>>> squares.pop(2) # remove an item with given key & return its value
4
>>> del squares[3] # remove item with given key, nothing returned
>>> squares
{1:1, 4:16}
>>> squares.clear() # removes all items, nothing returned, makes it empty
>>> squares
{}
>>> del squares # deletes a dictionary itself from the memory
>>> squares
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
squares
NameError: name ‘squares' is not defined
Updating dictionary: We can add new items or >>> dict1 = {‘name’:’Vijay’, ‘age’:40}
change the value of existing items. If key is >>> dict1[‘age’] = 35
already present, its value gets updated, else a >>> dict1
new key:value pair is added to the dictionary {‘name’:’Vijay’, ‘age’:35} #updating value
>>> dict1[‘address’] = ‘Lonere’
>>> dict1
{‘name’:’Vijay’, ‘age’:35, ‘address’:’Lonere’}
Basic operations on dictionary
1. Dictionary membership test: Using a keyword >>> print (‘name’ in dict1)
in, we can test if a key is in a dictionary or not. True
Not for values, only for keys. >>> print (‘adr’ in dict1)
False
>>> print(35 in dict1) # works for keys only
False
2. Traversing a dictionary: Output:
>>> squares 1 1
{1:1, 2:4, 3:9, 4:16, 5:25} 2 4
>>> for i in squares: 3 9
print (i, squares[i]) 4 16
5 25
Properties of dictionary keys: >>> dict = {1:’Vijay’, 2:’Amar’, 3:’Santosh’,
Dictionary values have no restrictions. They 2:’Umesh’}
can be any arbitrary python object, either >>> dict
standard objects or user-defined objects. {1:’Vijay’, 2:’Umesh’, 3:’Santosh’}
However, same is not true for keys.
1. More than one entry per key not allowed.
When duplicate keys are encountered during
assignment, the last assignment wins
2. Keys must be immutable. Which means >>> dict = {[1]:’Vijay’, 2:’Amar’, 3:’Santosh’}
you can use strings, numbers or tuples as Traceback (most recent call last):
dictionary keys but something like [‘key’] is File "<pyshell#3>", line 1, in <module>
not allowed dict = {[1]:'Vijay', 2:'Amar', 3:'Santosh'}
TypeError: unhashable type: 'list'
Built-in Functions and methods for dictionary
Sr. Method Description Example
No. >>> dict = {1:’Vijay’, 2:’Amar’, 3:’Santosh’}
1 clear() Removes all the elements from the >>> dict.clear()
dictionary >>> dict
{}
2 copy() Returns a copy of the dictionary >>> x=dict.copy()
>>> x
{1:’Vijay’, 2:’Amar’, 3:’Santosh’}
3 fromkeys() It creates a new dictionary with default >>>
value for all specified keys. If default dict=dict.fromkeys([‘Vijay’,’Meenakshi’],’Author’)
value is not specified, all keys are set to >>> dict
None. {'Vijay': 'Author', 'Meenakshi': 'Author'}
4 get() Returns the value of the specified key >>> dict1 = {‘name’:’Vijay’, ‘age’: 40}
>>> dict1.get(‘name’)
‘Vijay’
5 items() Returns a list containing the tuple for >>> for i in dict.items():
each key value pair print(i)
(1, ‘Vijay’)
(2, ‘Amar’)
(3, ‘Santosh’)
6 keys() Returns a list containing the dictionary’s >>> dict.keys()
keys dict_keys([1, 2, 3])
7 pop() Removes the element with the specified >>> print(dict.pop(2))
key ‘Amar’
8 popitem() Removes the last inserted key-value pair >>> dict.popitem()
(3, ‘Santosh’)
9 setdefault() Returns the value of the specified key. If >>> dict
the key does not exist; insert the key, {2:’Amar’, 3:’Santosh’}
with the specified value >>> dict.setdefault(1,’Vijay)
>>> dict
{2:’Amar’, 3:’Santosh’,1:’Vijay’}
10 update() Updates the dictionary with the >>> dict1={2:’Amar’, 4:’Santosh’}
specified key-value pairs. >>> dict2 ={1:’Vijay’, 3:’Umesh’}
>>> dict1.update(dict2)
>>> dict1
{2:’Amar’, 4:’Santosh’, 1:’Vijay’, 3:’Umesh’}
11 values() Returns a list of all the values in the >>> dict1.values()
dictionary dict_values([‘Amar’, ’Santosh’, ’Vijay’, ’Umesh])
Built-in functions of Dictionary
Sr. Function Description Example
No. >>> dict = {1:’Amar’, 2:’Vijay’, 3:’Santosh’}
1 all() Return True if all keys of the dictionary >>> all(dict)
are true (or if the dictionary is empty) True
2 any() Return True if any key of the dictionary >>> dict={}
is true. If the dictionary is empty, return >>> any(dict)
False False
3 len() Returns the length (no of items) in the >>> len(dict)
dictionary 3
4 sorted() Return a new sorted list of the keys in >>> dict1 = {2:’Amar’, 1:’Vijay’, 4:’Umesh’, 3:’Santosh’}
the dictionary >>> sorted(dict1)
[1, 2, 3, 4]
5 type() Returns the type of the passed variable >>> print(“Variable type: %s” %type (dict1))
Strings
• Strings are linear data structure in Python. It is a group of characters.
• Group of characters in the string are enclosed within set of single
quotes or double quotes.
• Python strings are immutable.
Function Example:
>>> a=“PYTHON”
>>> b=“Language”
len() function returns no o characters in a string >>> len(a)
6
min() function returns the smallest character in a >>> min(a)
string (Chronological order as per ASCII) ‘H’
max() function returns the largest character in a string >>> max(a)
(Chronological order as per ASCII) ‘Y’
deleting entire string >>> del a
>>> a
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
c
NameError: name ‘a' is not defined
String concatenation and multiplication >>> a + b
‘PYTHON Language’
>>> a*3
PYTHONPYTHONPYTHON
Traversing a string >>> for ch in a:
>>> index=0 print(ch,end=“”)
>>> while index < len(a) PYTHON
print(s[index], end=“”)
index = index+1
Strings are immutable >>> a[2]=‘z’
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
a[2]='z'
TypeError: 'str' object does not support item
assignment
‘in’ and ‘not in’ operator.
String slicing.
String comparison.
Special Characters in String
Sr. Escape Meaning Example
No. character
1 \n The new line character helps the programmer to >>> txt = “Guru\n99!”
insert a new line before or after a string. >>> print(txt)
Guru
99!
2 \\ This escape sequence allows the programmer to >>> txt = “Guru\\99!”
insert a backslash into the Python output. >>> print(txt)
Guru\99!
4 \ooo To get the integer value of an octal value, provide >>> txt = ‘\107\125\122\125’+ “99!”
a backslash followed by ooo or octal number in >>> print(txt)
double-quotes. GURU99!
It is done by printing in a backslash with three
octal equivalents in double quotes.
5 \b This escape sequence provides backspace to the Python >>> txt = “Guru\\99!”
string. It is inserted by adding a backslash followed by >>> print(txt)
“b”. Guru\99!
“b” here represents backslash.