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


No comments:

Post a Comment

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 ...