For Enquiry: 93450 45466

Data Structures in Python



Data Structures in python are used to store organised data.Your programs are almost built around data structures so that you can work effectively and efficiently with the data.The data structures are categorized into primitive data structures, built in data structures and user defined data structures.

Primitive data structures

These are the basic data structures, including ,integer , float , string and boolean ,which contain pure and simple forms of data.

Integers include whole numbers including negative and positive numbers.
Floats include rational numbers in decimal form.

# Example for Integer

x =3

y =3

print(x / y ) 

# Example for FLoat

x = 3.5

y =3.5

print(x + y) 

# Example for String

x = ‘True’

y = ‘False’

print(x + y) 

# Example for Boolean

x = True

y = False

print(x == y) 

The above will have an integer result as

1

7.0

TrueFalse

False

User Defined data structures

The various other user defined data structures include stack, queue,tree, linked list,hashmaps.

Stack

It is a linear data structure, which follows the principle of Last In First Out ‘.An example of stack could be your favourite books arranged on the table one above the other. You would add the most favourite book at the end (on the top), so that you can get it first.The first or the top element acts as a pointer for the current element in the stack.

Elements can be added on the top with a push, removed from the top with a pop. The length of the stack can be found with len method.

A real world implementation of stack could be the undo function.The word processor keeps record of the previous actions on stack so that the last action is on top, and you can always go to the last action performed with the undo function.

Queue

This is also a linear data structure with the principle of First In First Out or Last In Last Out. In a waiting line, the first person in the line will be served first and the new person at the last.

The elements in the queue can be added with enqueue and removed with the deque.Both these operations take O(1) time irrespective of the number of elements present in the queue.

Real world implementation of queues can be found in the network buffers and operating systems for job scheduling etc.

Trees

These are non linear data structures with nodes(vertices) and root.The root is the origin from where the nodes or vertices begin, therefore a node is a child for which root or node it comes from,and the preceding one is the parent.Leaves are the last nodes or the nodes without children.

A family tree could be the best example for the tree data structure.where the grandparents are the root and their children are nodes , and their children without any child are leaves 

A real world implementation of trees could be found in the structure of html tags. The html is the root tag, and the ones that come after are the nodes.

Linked lists

These are the linear data structures which are connected to each other with a pointer called next.The nodes in the linked lists carries data and can be stored anywhere in the memory unlike lists or arrays which are stored sequentially.A train could be the best example for linked lists. It has a locomotive (head) that powers the engine, rail cars(nodes) which carry freight(data).Unlike lists, random access of data is not supported in linked lists.

A real world implementation of linked lists can be found when you are using multiple applications.

Graphs

Graphs are non linear data structures , with a collection of objects(called nodes or vertices) with links(edges) in between.

A real world implementation would be when you are trying to find the shortest path using Google Maps or Uber

Hash Maps

Hashmaps are the data structures where the data is stored in pairs or with each data there is an associative or mapped value.

Their applications can be found in storing phone numbers with names, storing items with prices etc.

Checkout this Online Python Training by FITA. FITA provides a complete Django course where you will be building real-time projects like Bitly and Twitter bundled with Python training.

Built-in data structures

There are 4 built-in data structures in python. They are Lists, sets, tuples and dictionaries.

Lists

Lists in python are dynamic arrays which can store a series of items in an ordered manner, that is the order in which they were defined will be retained unlike dictionaries and sets.Lists are mutable or changeable, that is you can add, remove or update items from the list.

Defining or Creating List

An empty list can be created with empty square brackets or with list method, aAnd add elements to it.

# Example for creating list

t = [ ] # An empty python list 

y = [1,2,list,’with’,’values’]

z = list() # empty list with list function 

print(t, y,z)

The above program will have the output as,

[ ] [1,2,’list’,’with’,’values’] [ ]

Adding Elements to list

ELements or items can be added at the end to a defined list with the append method
Multiple elements can be added to the list with the extend() method simultaneously.
Adding elements at a specific position can be done using the insert() method, which takes two positional arguments, the index and the value.

# Example program for adding elements list

list_1 = [ ]

list_1.append(‘1’)

list_1.append([2,3,4])

print(‘modified list: ’,list_1)

list_1.extend([5,6,7])

list_1.extend([8])

print(‘modified list: ’,list_1)

list_1.insert(1,’Hi there’)

list_1.insert(1,’I am list’)

print(‘modified list: ’,list_1)

Which outputs

modified list: [1,[2,3,4]]

modified list: [1,[2,3,4],5,6,7,8]

modified list: [1,’I am list’,’Hi there’,[2,3,4],5,6,7,8]

Accessing elements from the list

Each element in the list has an address associated with it known as index. The index of the first element is 0, second is 1 and so on till the size of list less than one.Elements can also be accessed with negative indexing as -1 for the last, -2 for the second last and so on.
To get one element at a time, we can use for or while loops to iterate over the list and print the elements.
Also, you can use the slicing method to get specific elements from the list.
The list_name[start:end:step] will return the elements in the list_name from the start index until the end index , by removing or skipping step number of elements in between.

# Example program for accessing element from list

lst_1 = [1,’Hi there’,’I am list’,2]

lst_2 = [lst_1[0],lst_1[-1],lst_1[1],lst_1[-2]] 

print(‘first,last,second,second last elements from the lst_1 are: ’,lst_2)

for i in lst_1:

print(i, end=’ ‘)

print(lst_1[1:3:1])

Output

first,last,second,second last elements from the array 1 are: [1,2,’I am list’,’Hi there’]

1 Hi there I am list 2

[1,’I am list’]

Removing Elements from list

The last element from the list can be removed with pop() method.
A specific element can be removed with remove() method
All the elements can be removed simultaneously with the clear() method

# Example program for removing elements from list

x = [‘A’, ‘complete’,’python’, ‘tutorial’,’at’,’FITA’ ]

x.pop()

print(x)

x.remove(‘python’)

print(x)

x.clear()

print(x)

Which outputs

[‘A’, ‘complete’,’python’, ‘tutorial’,’at’ ]

[‘A’, ‘complete’, ‘tutorial’,’at’ ]

[ ]

The other various methods that can be applied to a list are, sorted,len, index,count etc.

Dictionaries

Dictionaries are used to store values in pairs, usually as key and its value. For example, 

Storing name of persons as keys and their phone numbers as values.

Creating dictionaries

# Example for creating dictionaries

# an empty dictionary

dict_1 = { } 

dict_2 = dict()

dict_1 = {‘name’ :’rosy’,phone:1234} # dictionary with values

print(dict_1,dict_2)

Output

{‘name’ :’rosy’,’phone’:1234} { }

Adding or updating key,value to dictionary

dict_2[‘names’] = [‘rachael‘,’ruby’,] # adding new value

dict_2[‘phone’] = [8520,7410] 

dict_1[‘phone’’] = 9876 # updating existing value

print(dict_1,dict_2)

Output

{ ‘name’: ’rosy’, phone:9876 } { ‘name’: [’racheal’,’ruby’], ’phone’: [8520,7410] }

Other methods that can be applied on dictionaries,are get(),keys(),values(),items().

Tuple

Tuples are the same as lists except that they are immutable or unchangeable; that is their value once entered cannot be changed or updated or deleted.

# Example program for tuple 

#empty tuple

tup_1 = ()

tup_1 += (1,2,3,) # adding elements to tuple

# tup_1[1] = 2 this would give a type error

x = tup_1[0] # accessing element from tuple

print(tup_1)

Output

(1,2,3)

Sets

Sets in python are as same as sets you might have learned in high school mathematics.They are mutable and cannot have repeated values.sets are unordered,that is their order is not reserved after assigning values to them.The different operations that can be performed on sets includes union,intersection,difference, symmetric difference.

Creating ,adding and removing elements to a set

Sets are denoted with curly { } braces around values separated by commas.

# Example program for sets

set_1 = { 2,3,4}

 # adding elements to sets

set_1.add(4)

set_1.add(1)

print(set_1)

# removing an elements from sets

set_1.remove(3)

print(set_1)

# clearing the set

set_1.clear()

print(set_1)

Output

{1, 2, 3, 4}

{1, 2, 4}

set()

You might have noticed that the set function filtered the values to be unique.

# Example program for union operation on sets

set_1 = { 2,3,4}

set_2 = {‘python programming’}

# union on sets

print(set_1|set_2)

print(set_1.union(set_2))

The above two print statements will have the same output as the unique elements in both the sets

{‘python programming’,2,3,4}

 

# Example program for intersection operation on sets

set_1 = set(‘2,3’)

set_2 = set(‘python programming 2’)

# intersection on sets

print(set_1 & set_2)

print(set_1.intersection(set_2))

The above two print statements will have the same output as the same elements in both the sets.

{‘2’}

Similarly you can perform other functions like difference , symmetric difference etc.

This was all about built in data structures in python.Now let’s talk about user defined data structures in python.

This was all about data structures in python with its types and implementations and real world applications..To get in-depth knowledge of Python along with its various applications and real-time projects, you can enroll in Python Course in Chennai or Python Course in Bangalore by FITA at an affordable price, which includes real time projects with certification, support and career guidance assistance.




Recent Post:


Quick Enquiry

Please wait while submission in progress...


Contact Us

Chennai, Bangalore & Online

  93450 45466

Coimbatore

 95978 88270

Pondicherry

93635 21112

Madurai

97900 94102

Tirupur

99401 22502

For Hiring

 93840 47472
 hr@fita.in

Corporate Training

 90036 23340


FITA Academy Branches

Chennai

FITA Academy - Velachery
Plot No 7, 2nd floor,
Vadivelan Nagar,
Velachery Main Road,
Velachery, Chennai - 600042
Tamil Nadu

    :   93450 45466

FITA Academy - Anna Nagar
No 14, Block No, 338, 2nd Ave,
Anna Nagar,
Chennai 600 040, Tamil Nadu
Next to Santhosh Super Market

    :   93450 45466

FITA Academy - T Nagar
05, 5th Floor, Challa Mall,
T Nagar,
Chennai 600 017, Tamil Nadu
Opposite to Pondy Bazaar Globus

    :   93450 45466

FITA Academy - Tambaram
Nehru Nagar, Kadaperi,
GST Road, West Tambaram,
Chennai 600 045, Tamil Nadu
Opposite to Saravana Jewellers Near MEPZ

    :   93450 45466

FITA Academy - Thoraipakkam
5/350, Old Mahabalipuram Road,
Okkiyam Thoraipakkam,
Chennai 600 097, Tamil Nadu
Next to Cognizant Thoraipakkam Office
& Opposite to Nilgris Supermarket

    :   93450 45466

FITA Academy - Porur
17, Trunk Rd,
Porur
Chennai 600116, Tamil Nadu
Above Maharashtra Bank

    :   93450 45466

FITA Academy - Pallikaranai
335A, 13th Main Rd,
Ram Nagar South Extn,
Pallikaranai, Chennai,
Tamil Nadu 600100

    :   93450 45466

Bangalore

FITA Academy Marathahalli
No 7, J J Complex,
ITPB Road, Aswath Nagar,
Marathahalli Post,
Bengaluru 560037

    :   93450 45466

Coimbatore

FITA Academy - Saravanampatty
First Floor, Promenade Tower,
171/2A, Sathy Road, Saravanampatty,
Coimbatore - 641035
Tamil Nadu

    :   95978 88270

FITA Academy - Singanallur
348/1, Kamaraj Road,
Varadharajapuram, Singanallur,
Coimbatore - 641015
Tamil Nadu

    :   95978 88270

Other Locations

FITA Academy - Madurai
No.2A, Sivanandha salai,
Arapalayam Cross Road,
Ponnagaram Colony,
Madurai - 625016, Tamil Nadu

    :   97900 94102

FITA Academy - Pondicherry
410, Villianur Main Rd,
Sithananda Nagar, Nellitope,
Puducherry - 605005
Near IG Square

    :   93635 21112

FITA Academy - Tiruppur
61D, Poongodi Towers 2nd floor,
Periyar Colony Bus Stop,
Tirupur - 641 652

    :   9940122502

Read More Read less
  • Are You Located in Any of these Areas

    Adambakkam, Adyar, Akkarai, Alandur, Alapakkam, Alwarpet, Alwarthirunagar, Ambattur, Ambattur Industrial Estate, Aminjikarai, Anakaputhur, Anna Nagar, Anna Salai, Arumbakkam, Ashok Nagar, Avadi, Ayanavaram, Besant Nagar, Bharathi Nagar, Camp Road, Cenotaph Road, Central, Chetpet, Chintadripet, Chitlapakkam, Chengalpattu, Choolaimedu, Chromepet, CIT Nagar, ECR, Eechankaranai, Egattur, Egmore, Ekkatuthangal, Gerugambakkam, Gopalapuram, Guduvanchery, Guindy, Injambakkam, Irumbuliyur, Iyyappanthangal, Jafferkhanpet, Jalladianpet, Kanathur, Kanchipuram, Kandhanchavadi, Kandigai, Karapakkam, Kasturbai Nagar, Kattankulathur, Kattupakkam, Kazhipattur, Keelkattalai, Kelambakkam, Kilpauk, KK Nagar, Kodambakkam, Kolapakkam, Kolathur, Kottivakkam, Kotturpuram, Kovalam, Kovilambakkam, Kovilanchery, Koyambedu, Kumananchavadi, Kundrathur, Little Mount, Madambakkam, Madhavaram, Madipakkam, Maduravoyal, Mahabalipuram, Mambakkam, Manapakkam, Mandaveli, Mangadu, Mannivakkam, Maraimalai Nagar, Medavakkam, Meenambakkam, Mogappair, Moolakadai, Moulivakkam, Mount Road, MRC Nagar, Mudichur, Mugalivakkam, Muttukadu, Mylapore, Nandambakkam, Nandanam, Nanganallur, Nanmangalam, Narayanapuram, Navalur, Neelankarai, Nesapakkam, Nolambur, Nungambakkam, OMR, Oragadam, Ottiyambakkam, Padappai, Padi, Padur, Palavakkam, Pallavan Salai, Pallavaram, Pallikaranai, Pammal, Parangimalai, Paruthipattu, Pazhavanthangal, Perambur, Perumbakkam, Perungudi, Polichalur, Pondy Bazaar, Ponmar, Poonamallee, Porur, Pudupakkam, Pudupet, Purasaiwakkam, Puzhuthivakkam, RA Puram, Rajakilpakkam, Ramapuram, Red Hills, Royapettah, Saidapet, Saidapet East, Saligramam, Sanatorium, Santhome, Santhosapuram, Selaiyur, Sembakkam, Semmanjeri, Shenoy Nagar, Sholinganallur, Singaperumal Koil, Siruseri, Sithalapakkam, Srinivasa Nagar, St Thomas Mount, T Nagar, Tambaram, Tambaram East, Taramani, Teynampet, Thalambur, Thirumangalam, Thirumazhisai, Thiruneermalai, Thiruvallur, Thiruvanmiyur, Thiruverkadu, Thiruvottiyur, Thoraipakkam, Thousand Light, Tidel Park, Tiruvallur, Triplicane, TTK Road, Ullagaram, Urapakkam, Uthandi, Vadapalani, Vadapalani East, Valasaravakkam, Vallalar Nagar, Valluvar Kottam, Vanagaram, Vandalur, Vasanta Nagar, Velachery, Vengaivasal, Vepery, Vettuvankeni, Vijaya Nagar, Villivakkam, Virugambakkam, West Mambalam, West Saidapet

    FITA Velachery or T Nagar or Thoraipakkam OMR or Anna Nagar or Tambaram or Porur or Pallikaranai branch is just few kilometre away from your location. If you need the best training in Chennai, driving a couple of extra kilometres is worth it!