Data structures are a way of organizing and storing data so that they can be accessed and worked with efficiently. They define the relationship between the data, and the operations that can be performed on the data. Data structures unlike data types not only store a value but collection of values in various format.
x=\[1,2,3,4,5,6,7\]
print(type(x))
Show Output
<class 'list'>
insert() function is used to insert an element in the list at the specified index
x.insert(2,10)
Show Output
print(x)
[1, 2, 10, 3, 4, 5, 6, 7]
append() functions is used to add an element to the end of a list.
x.append(20)
Show Output
print(x)
[1, 2, 10, 3, 4, 5, 6, 7, 20]
len() function returns the length of a list which will be the total number of elements present in the list
len(x)
Show Output
print(len(x))
9
remove() function is used to remove a specific element from the list
x.remove(7)
Show Output
print(x)
[1, 2, 10, 3, 4, 5, 6, 20]
pop() function removes and returns the last element from the list
x.pop()
show output
print(x)
[1, 2, 10, 3, 4, 5, 6]
del is also used to delete an element from the list , it deletes the element specified at the index
del x\[4\]
Show Output
print(x)
[1, 2, 10, 3, 5, 6]
extend() function in list is used to extend one list with another
x=\['cisco','juniper','hp'\]
y=\['router','switch','firewall'\]
x.extend(y)
Show Ouput
print(x)
['cisco', 'juniper', 'hp', 'router', 'switch', 'firewall']
Sort() function sorts the list in ascending order.Sorting is done on the basis of ASCII values. You can also decide the sorting order by setting the reverse parameter to either true or false
x = \['cisco', 'HP', 'juniper', 'router', '7200'\]
x.sort()
Show Output
print(x)
['7200', 'HP', 'cisco', 'juniper', 'router']
Below example shows sort() function with reverse parameter = True
x = \['cisco', 'HP', 'juniper', 'router', '7200'\]
x.sort(reverse=True)
Show Output
print(x)
['router', 'juniper', 'cisco', 'HP', '7200']
sorted() function in list is used to sort the list in ascending order.The only difference between the sort() function and the sorted function is that the sort() function will modify the list it is called on. The sorted() function will create a new list containing a sorted version of the list it is given.
x = \['cisco', 'HP', 'juniper', 'router', '7200'\]
Show Output
print(sorted(x))
['7200', 'HP', 'cisco', 'juniper', 'router']
print(x)
['cisco', 'HP', 'juniper', 'router', '7200']
The max() function returns the item with the highest value .this is done with help of ASCII values, ASCII values of small letter is the highest and lowest for numbers
x=\['INR','12','456','dollar'\]
Show Output
print(max(x))
dollar
The min() function returns the item with the lowest value
Show Output
print(min(x))
12
Slicing in list works in same way as it does in strings(We have already studied string slicing in LAB 2: Basics of Programming)
x = \['pune','mumbai','nagpur','nasik','kolhapur'\]
print(x\[3\])
Show Output
'nasik'
print(x\[1:4\])
Show Ouput
['mumbai', 'nagpur', 'nasik']
print(x\[0:5:2\])
Show Output
['pune', 'nagpur', 'kolhapur']
print(x\[-1:-4:-1\])
Show Output
['kolhapur', 'nasik', 'nagpur']
Nested list is a list with in another list.Below example shows nested list
city = \['pune','mumbai','nagpur','nasik','kolhapur'\]
state = \['Maharashtra','Gujarat','kerala',city\]
country = \['india','singapore','malaysia','sri lanka',state\]
Show Output
print(country)
['india', 'singapore', 'malaysia', 'sri lanka', ['Maharashtra', 'Gujarat', 'kerala', ['pune', 'mumbai', 'nagpur', 'nasik', 'kolhapur']]]
Accessing items within nested list.Here we are trying to access the element ‘kolhapur’
print(country\[4\]\[3\]\[4\])
Show Output
'kolhapur'
In this example we are trying to access element ‘kerala’
print(country\[4\]\[2\])
Show Output
'kerala'
List Comprehension is an elegant and easy way to define and create lists.
Creating a list using for loop
squares=\[\]
for n in range(10):
squares.append(n\*\*2)
print(squares)
Show Output
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Implementing the same using list comprehension
squares = \[n\*\*2 for n in range(10)\]
print(squares)
Show Output
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Example : This example sorts the odd and even numbers from a list and save them in new list
x=\[12,23,45,67,87,2\]
list\_even=\[\]
list\_odd=\[\]
for i in x:
if i%2==0:
list\_even.append(i)
else:
list\_odd.append(i)
print('List\_even',list\_even)
print('List\_odd',list\_odd)
Show Output
List_even [12, 2]
List_odd [23, 45, 67, 87]
Implementing the same using List comprehension
x=\[12,23,45,67,87,2\]
list\_even=\[i for i in x if i%2==0\]
print('List\_even',list\_even)
list\_odd=\[i for i in x if i%2!=0\]
print('List\_odd',list\_odd)
Show Output
List_even [12, 2]
List_odd [23, 45, 67, 87]
Since tuples are immutable there are no functions available to add or remove elements from tuples.You can still access elements from tuples using indexing as we did in list.
x=('sam','rahul','sameer','divya')
print(x\[3\])
Show Output
divya
To add elements in tuples we have to convert it into list and then use list functions to add or remove elements and then convert the list back to tuple
tup = (1,2,'jacky','nilam',4,5)
y = list(tup)
print(type(y))
y.append('Priya')
tup=tuple(y)
print(type(tup))
print('new tuple',tup)
Show Output
<class 'list'>
<class 'tuple'>
new tuple (1, 2, 'jacky', 'nilam', 4, 5, 'Priya')
dc = {'vendor':'cisco','device':'router','ios':15.4}
print(type(dc))
Show Output
<class 'dict'>
keys() function returns a list of all keys in the dictionary
print(dc.keys())
Show Output
dict_keys(['vendor', 'device', 'ios'])
values() function returns a list of all values in the dictionary
print(dc.values())
Show Output
dict_values(['cisco', 'router', 15.4])
items() function returns a list of all key : value pair in the dictionary
print(dc.items())
Show Output
dict_items([('vendor', 'cisco'), ('device', 'router'), ('ios', 15.4)])
To add new item ( key : value ) in a dictionary
dc\['series'\] = 7200
Show Output
print(dc)
{'vendor': 'cisco', 'device': 'router', 'ios': 15.4, 'series': 7200}
To change value of existing key in a dictionary
dc\['vendor'\] = 'juniper'
Show Output
print(dc)
{'vendor': 'juniper', 'device': 'router', 'ios': 15.4, 'series': 7200}
Accessing values of any particular key in a dictionary
dc\['device'\]
Show Output
router
pop() method removes an element from the dictionary. It removes the element which is associated to the specified key. If specified key is present in the dictionary, it remove and return its value.
dc.pop('ios')
Show Output
15.4
print(dc)
{'vendor': 'juniper', 'device': 'router', 'series': 7200}
The popitem() method removes the item that was last inserted into the dictionary and returns it.
dc.popitem()
Show Output
('series', 7200)
dc = {'fruit':'apple','vegtable':'potato','junk':{'drinks':'coke','burger':'Mc D','pizza':'dominos'}}
Accessing items in nested dictionary
dc\['junk'\]\['pizza'\]
Show Output
'dominos'
Changing values of a particular key in nested dictionary
dc\['junk'\]\['pizza'\]='pizza hut'
Show Output
print(dc)
{'fruit': 'apple', 'vegtable': 'potato', 'junk': {'drinks': 'coke', 'burger': 'Mc D', 'pizza': 'pizza hut'}}
deleting item from nested dictionary
del dc\['junk'\]\['pizza'\]
Show Output
print(dc)
{'fruit': 'apple', 'vegtable': 'potato', 'junk': {'drinks': 'coke', 'burger': 'Mc D'}}
Dictionary comprehension is simplest and elegant way of creating dictionary
my\_dic={}
for i in range (5):
for j in range(5):
my\_dic\[i\]=j
print(my\_dic)
Show Output
{0: 4, 1: 4, 2: 4, 3: 4, 4: 4}
Implementing the same using dictionary comprehension
mu\_dic={i:j for i in range(5) for j in range(5)}
Show Output
{0: 4, 1: 4, 2: 4, 3: 4, 4: 4}
names = \['tony','captain','batman'\]
heros = \['stark','america','bruce'\]
dic={}
for names,heros in zip(names,heros):
dic\[names\]=heros
print(dic)
Show Output
{'tony': 'stark', 'captain': 'america', 'batman': 'bruce'}
Implementing the same using dictionary comprehension
names = \['tony','captain','batman'\]
heros = \['stark','america','bruce'\]
my\_dict={name:hero for name,hero in zip(names,heros)}
print(my\_dict)
Show Output
{'tony': 'stark', 'captain': 'america', 'batman': 'bruce'}
Similar items are counted only nce in set
set1 = {'c','c++','java','python','python','java'}
print(set1)
Show Output
{'c', 'c++', 'python', 'java'}
Since sets are unordered collection of data we cannot perform indexing operation on sets
Below syntax show how to add element into a set, this items will get added randomly anywhere in the set.
set1.add('ansible')
print(set1)
Show Output
{'python', 'ansible', 'c', 'c++', 'java'}
Below syntax shows how to delete an item from set
set1.remove('c++')
print(set1)
Show Output
{'python', 'ansible', 'c', 'java'}
pop() function removes and returns any arbitrary element from the set
set1.pop()
print(set1)
Show Output
'python'
{'ansible', 'c', 'java'}
discard() method is also used to remove an element from the set the only difference between discard() and remove() is that remove() returns an error if the item to be deleted is not present in the set where as discard() function doesn’t show any error
set.discard('php')
clear() is used to clear the entire set
set1.clear()
Show Output
print(set1)
set()
intrsection() method returns a set that contains the similarity between two or more sets.
setA = {1,2,6,8,10,15,20}
setB = {2,6,12,15,16}
print(setA.intersection(setB))
Show Output
{2, 6, 15}
difference() returns the difference between two given sets.
print(setA.difference(setB))
Show Output
{8, 1, 10, 20}
The union() method returns a set that contains all items from the original set, and all items from the specified sets
print(setA.union(setB))
Show Output
{1, 2, 6, 8, 10, 12, 15, 16, 20}
The issubset() method returns True if all elements of a set A are present in another set B which is passed as an argument and returns false if all elements not present.
setC = {1,2,6,8}
print(setC.issubset(setA))
Show Output
True
The issuperset() method returns True if all elements of a set A occupies set B which is passed as an argument and returns false if all elements of B not present in A.
print(setA.issuperset(setC))
Show Output
True