Sunday, May 17, 2020

Python Blog1: List, Tuples, Dictionary and Set

Data Structures in Python


Introduction

In this blog we will look at some of the most important data structures in python.Braodly we will discuss the following

  • lists
  • tuples
  • dictionary
  • set

The below sections will walk you through each of the individual elements along with the functions used with each

List

List is the most commonly used data structure in python.It is very powerful in the sense that it can handle huge volume of data and is most suitable to perform intermediate operations. In the below sections we will look at how to initialise a list, indexing operations,updation,etc

Creating a List


a = [1,2,3,4,5,6]
print("value of a is :",a, "and type of a is ",type(a))
value of a is : [1, 2, 3, 4, 5, 6] and type of a is  <class 'list'>


Creating an empty List

b=[]
print("value of b is :",b, "and type of b is ",type(b))
value of b is : [] and type of b is  <class 'list'>


Length of the List

a = [1,2,3,4,5,6]
len(a)
6


Two Dimensional Lists or List of Lists

c = [[1,2],[3,4]]
c
[[1, 2], [3, 4]]
len(c)
2


List of Varied Length

d=[[1,4],2,5,[3,4,6,7],[5,6]]
d
[[1, 4], 2, 5, [3, 4, 6, 7], [5, 6]]
type(d)
<class 'list'>
type(d[0])
<class 'list'>
type(d[1])
<class 'int'>


Indexing in List

Index position in python starts from zero as against in R where the index poistion starts from 1

c=[3,2,5,6]
c[0]
3
c[3]
6
c[len(c)-1]
# c[7] will give an out of range error
6


Accessing the First and Last element in c

c=[3,2,5,6]
print("The first element is ",c[-len(c)])
The first element is  3
print("The last element is ",c[len(c)-1])
The last element is  6


Lets look at some List functions

x = [10,31,42,3,54,25,26,17,48,9]
x
[10, 31, 42, 3, 54, 25, 26, 17, 48, 9]


Append an element with a value 11 to x

x = [10,31,42,3,54,25,26,17,48,9]
x.append(11)
print(x)
[10, 31, 42, 3, 54, 25, 26, 17, 48, 9, 11]


Append a list to x

x = [10,31,42,3,54,25,26,17,48,9]
x.append([11,12])
print(x)
[10, 31, 42, 3, 54, 25, 26, 17, 48, 9, [11, 12]]

We can see that the list containing 11 and 12 was added to x but as a list

Extend

Using extend function we can add elements to x as individual units. The length of x will increase by the number of elements in the argument

x = [10,31,42,3,54,25,26,17,48,9]
x.extend([5,7,9,7,8,9])
print(x)
[10, 31, 42, 3, 54, 25, 26, 17, 48, 9, 5, 7, 9, 7, 8, 9]
print(len(x))
16


Pop

Removes elements from a list based on the argument provided

x = [10,31,42,3]
x.pop()
3
x
[10, 31, 42]


Deleting element at index position 2

We can see that 42 is present at index position 2. We can remove it using pop

x = [10,31,42,3]
x.pop(2)
42
x
[10, 31, 3]


Remove

Removes the first occurence of an element from list

x = [1,1,2,3,4,4]
x.remove(1)
x
[1, 2, 3, 4, 4]


count

Count the occurence of an element within a list

x = [1,1,2,3,4,4]
x.count(1)
2


del

Elements within a list can also be deleted by del function.It takes positional indices as argument

x = [1,1,2,3,4,4]
del x[5]
x
[1, 1, 2, 3, 4]


delete the elements from zero index position to second index position

x = [1,1,2,3,4,4]
del x[:3]
x
[3, 4, 4]


Tuple

A tuple is similar to list but the only difference is that its contents cant be altered.In that sense a tuple is immutable while a list is mutable(as we saw in the above examples)

creating a tuple


t=(10,11,12,13,14)
print("contents in t are ",t," and type of t is ",type(t))
contents in t are  (10, 11, 12, 13, 14)  and type of t is  <class 'tuple'>
print("lenth of t is ",len(t))
lenth of t is  5


Indexing a tuple


t=(10,11,12,13,14)
t[0]
10
t[3]
13
t[len(t)-1]
14


Accessing the First and Last element in t

t=(10,11,12,13,14)
print("The first element is ",t[-len(t)])
The first element is  10
print("The last element is ",t[len(t)-1])
The last element is  14


Tuples are immutable

t=(10,11,12,13,14)
#t[0]=100

t[0]=100 will give the error message-“tuple object doesnt support item assignment”. This shows that tuples are immutable

Mutable Objects within tuples are however mutable

t=(10,[11,110],12,13,14)
t[1][0]=100
print(t)
(10, [100, 110], 12, 13, 14)

As shown above,element at index position 1 is a list. In the above code we have tried to change the first element of the list with 100 and since items within Lists are mutable so the first element of List can be changed


Assigning a single element as tuple

t=(10)
print(type(t))
<class 'int'>
u=(10,)
print(type(u))
<class 'tuple'>
v=tuple([10])
print(type(v))
<class 'tuple'>


Dictionary

A dictionary is an unordered collection of items. It is represented by a key value pair.Dictionary can have Strings,integers, floats, characters as Keys. We will look at its meaning in more detail with below examples.Dictionaries are optimized to retrieve values when the key is known.


creating a dictionary


d1 = {'empname':'Rahul','empid':234}
d1
{'empname': 'Rahul', 'empid': 234}

There are two keys- empname and empid There are correspondingly two values-Rahul and 234

Access key and value of dictionary


d1 = {'empname':'Rahul','empid':234}
print(d1.keys())
dict_keys(['empname', 'empid'])
print(d1.values())
dict_values(['Rahul', 234])

You can check the type of keys and values yourself

More light on key and value of dictionary


d2 = {'empname':['Rahul','Rohit','Divya'],'empid':[234,456,234],3:[1,'text'],2.3:3,'c':(4,5,6)}
print(d2)
{'empname': ['Rahul', 'Rohit', 'Divya'], 'empid': [234, 456, 234], 3: [1, 'text'], 2.3: 3, 'c': (4, 5, 6)}

Dictionary can have Strings,integers, floats, characters as Keys However as values we can have both native and advanced data structures such as Lists,tuples


Indexing in dictionary

lets try and access values for key ‘c’


d2 = {'empname':['Rahul','Rohit','Divya'],'empid':[234,456,234],3:[1,'text'],2.3:3,'c':(4,5,6)}
print(d2['c'])
(4, 5, 6)


Indexing in dictionary

lets try and update values for key ‘c’ and ‘empname’


d2 = {'empname':['Rahul','Rohit','Divya'],'empid':[234,456,234],3:[1,'text'],2.3:3,'c':(4,5,6)}
# d2['c'][0]=5 will get an error as tuples are immutable
d2['empname'][0]='Rahul_updated'
print(d2)
{'empname': ['Rahul_updated', 'Rohit', 'Divya'], 'empid': [234, 456, 234], 3: [1, 'text'], 2.3: 3, 'c': (4, 5, 6)}


Adding a new key value pair to a dictionary


d2 = {'empname':['Rahul','Rohit','Divya'],'empid':[234,456,234],3:[1,'text'],2.3:3,'c':(4,5,6)}
d2['new']='new_value'

print(d2)
{'empname': ['Rahul', 'Rohit', 'Divya'], 'empid': [234, 456, 234], 3: [1, 'text'], 2.3: 3, 'c': (4, 5, 6), 'new': 'new_value'}


Set

A set is a collection which is unordered,unique and unindexed

creating a set


x = set(['cat','dog','goat','cat','lion'])
print(x)
{'dog', 'lion', 'goat', 'cat'}


Updating a set

x = set(['cat','dog','goat','cat','lion'])
x.add('rahul')
print(x)
{'dog', 'goat', 'cat', 'rahul', 'lion'}


Final Comments

The aforementioned content should give you an understanding of how to store data and iterate through the element. Auxillary functions provide enhanced understanding of how to play around with the data structure.In the next blog, we will look at arrays


Saturday, May 2, 2020

Book Review: Who moved my interest date ?

Who Moved My Interest Rate: Leading the Reserve Bank Through Five Turbulent YearsWho Moved My Interest Rate: Leading the Reserve Bank Through Five Turbulent Years by Duvvuri Subbarao
My rating: 4 of 5 stars

When it comes to RBI Governors, all we can think of is either Manmohan Singh or Raghuram Rajan. If there were a scale to measure the personality evolution of central bank Governors in India, both of them would represent the ends of the scale. People seldom talk about the ones in between. Duvvuri Subbarao, 22nd Governor of RBI, came to the helm amid one of the most severe recession of modern times. His book mostly revolves around the time from 2008 to 2013 and gives a gist of the development that took place. I have broken down the review based on some of the important events in the Book:

• From North Block to Mint Road: Being the Finance secretary to the PM's office, his appointment as the RBI governor came as surprise to most in the speculation market.It was the PM who had convinced Chidambaram to consider Subbarao as the Economic Advisor earlier on. It was Chidambaram's turn to nudge the PM this time.
• Baptism by Fire: There was hardly any transition time between jobs for Subbarao. With just a few days in office, he had to face the Global crisis of 2008. The ripples of the meltdown were felt in most devoloped economies. India, however, remained immune to the otherwise global pandemic. Therefore,some credit of India coming out unscathed must be given to Subbarao. His tenure endured stiff challenges. Soverighn crisis of EU,Rupee Tantrum, Import Export Balance, Taper Tantrum
• Inflation Targeting:RBI, over the year, has worked on a more holistic kind of approach without focussing too much on single metric. Hence when the subject of engineering the monetary policy based on an inflation target was brought up, Subbarao was forthright in his stance. He suggested that such a framework would not ensure economic balance as seen in New Zealand during the 90's. Several studies were carried out under the aegis of Urjit patel (another RBI governor) who eventually suggested to peg monetary policy against inflation. India, under the leadership of PM Modi eventually brough the inflation targeting framework into effect
• Rupee Tantrum (read as falling rupee), Taper tantrum (slowing down of the Quantitaive easing program), Gold Reserves, being at loggerheads with the Govt on inflation and price stability were some of the highlights of his career where he had to manage market expectations while also doing the right things


View all my reviews

Web Scraping Tutorial 4- Getting the busy information data from Popular time page from Google

Popular Times Popular Times In this blog we will try to scrape the ...