Python

LAB 4: Data Structures in Python

Python

LAB 4: Data Structures in Python

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.

List

  • A list is a data structure that holds an ordered collection of items i.e. you can store a
  • sequence of items in a list.
  • The items of list should be enclosed in square brackets
  • Lists are mutable that means you can add, remove or delete items in list

List Functions

x=[1,2,3,4,5,6,7]
print(type(x))
<class 'list'>

insert() function is used to insert an element in the list at the specified index

x.insert(2,10)
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)
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)
print(len(x))
9

remove() function is used to remove a specific element from the list

x.remove(7)
print(x)
[1, 2, 10, 3, 4, 5, 6, 20]

pop() function removes and returns the last element from the list

x.pop()
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]
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)
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()
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)
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']
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']
print(max(x))
dollar

The min() function returns the item with the lowest value

print(min(x))
12

Slicing in List

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])
'nasik'
print(x[1:4])
['mumbai', 'nagpur', 'nasik']
print(x[0:5:2])
['pune', 'nagpur', 'kolhapur']
 print(x[-1:-4:-1])
['kolhapur', 'nasik', 'nagpur']

Nested List

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]
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])
'kolhapur'

In this example we are trying to access element ‘kerala’

print(country[4][2])
'kerala'

List Comprehension

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)
[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)
[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)
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)
List_even [12, 2]
List_odd [23, 45, 67, 87]

Tuples in Python

  • Tuples are used to hold together multiple objects in ordered sequence
  • Tuples are immutable like strings i.e. you cannot modify tuples.
  • Tuples are defined by specifying items separated by commas within a pair of parentheses.
  • Tuples are usually used in cases where the values or elements of tuples will not change

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])
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)
<class 'list'>
<class 'tuple'>
new tuple (1, 2, 'jacky', 'nilam', 4, 5, 'Priya')

Why to use tuples ?

  • Tuples are lighter-weight and are more memory efficient and often faster if used in appropriate places.
  • When using a tuple, you protect against accidental modification when passing it between functions.
  • Tuples, being immutable, can be used as a key in a dictionary, which we’re about to learn about.

Dictionary in Python

  • A dictionary is like an address-book where you can find the address or contact details of a person by knowing only his/her name i.e. we associate keys (name) with values (details).
  • Keys in dictionary should always be immutable object (like strings) but the Values of dictionary can be mutable.
  • The elements/items in dictionary are enclosed within curly brackets
dc = {'vendor':'cisco','device':'router','ios':15.4}
print(type(dc))
<class 'dict'>

keys() function returns a list of all keys in the dictionary

print(dc.keys())
dict_keys(['vendor', 'device', 'ios'])

values() function returns a list of all values in the dictionary

print(dc.values())
dict_values(['cisco', 'router', 15.4])

items() function returns a list of all key : value pair in the dictionary

print(dc.items())
dict_items([('vendor', 'cisco'), ('device', 'router'), ('ios', 15.4)])

To add new item ( key : value ) in a dictionary

dc['series'] = 7200
print(dc)
{'vendor': 'cisco', 'device': 'router', 'ios': 15.4, 'series': 7200}

To change value of existing key in a dictionary

dc['vendor'] = 'juniper'
print(dc)
{'vendor': 'juniper', 'device': 'router', 'ios': 15.4, 'series': 7200}

Accessing values of any particular key in a dictionary

dc['device']
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')
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()
('series', 7200)

Nested Dictionary

dc = {'fruit':'apple','vegtable':'potato','junk':{'drinks':'coke','burger':'Mc D','pizza':'dominos'}}

Accessing items in nested dictionary

dc['junk']['pizza']
'dominos'

Changing values of a particular key in nested dictionary

dc['junk']['pizza']='pizza hut'
print(dc)
{'fruit': 'apple', 'vegtable': 'potato', 'junk': {'drinks': 'coke', 'burger': 'Mc D', 'pizza': 'pizza hut'}}

deleting item from nested dictionary

del dc['junk']['pizza']
print(dc)
{'fruit': 'apple', 'vegtable': 'potato', 'junk': {'drinks': 'coke', 'burger': 'Mc D'}}

Dictionary Comprehension

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)
{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)}
{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)
{'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)
{'tony': 'stark', 'captain': 'america', 'batman': 'bruce'}

Sets in Python

  • Sets are unordered collections of simple objects. These are used when the existence of any object in a collection is more important than the order or how many times it occurs.
  • Sets are Mutable data types

Similar items are counted only nce in set

set1 = {'c','c++','java','python','python','java'}
print(set1)
{'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)
{'python', 'ansible', 'c', 'c++', 'java'}

Below syntax shows how to delete an item from set

set1.remove('c++')
print(set1)
{'python', 'ansible', 'c', 'java'}

pop() function removes and returns any arbitrary element from the set

set1.pop()
print(set1)
'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()
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))
{2, 6, 15}

difference() returns the difference between two given sets.

print(setA.difference(setB))
{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))
{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))
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))
True