• Chennai, Bangalore & Online: 93450 45466Coimbatore: 95978 88270Madurai: 97900 94102

  • 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

      93450 45466

    Bangalore

     93450 45466

    Coimbatore

     95978 88270

    For Hiring

     93840 47472
     hr@fita.in

    Corporate Training

     90036 23340


    FITA Academy Branches

    Chennai
    Bangalore
    Coimbatore
    Other Locations
    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 and Opposite to Nilgris Supermarket

        :   93450 45466

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

        :   93450 45466

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

        :   93450 45466

    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

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

        :   97900 94102

  • Trending Courses

    JAVA Training In Chennai Dot Net Training In Chennai Software Testing Training In Chennai Cloud Computing Training In Chennai AngularJS Training in Chennai Big Data Hadoop Training In Chennai Android Training In Chennai iOS Training In Chennai Web Designing Course In Chennai PHP Training In Chennai Digital Marketing Course In Chennai SEO Training In Chennai

    Oracle Training In Chennai Selenium Training In Chennai Data Science Course In Chennai RPA Training In Chennai DevOps Training In Chennai C / C++ Training In Chennai UNIX Training In Chennai Placement Training In Chennai German Classes In Chennai Python Training in Chennai Artificial Intelligence Course in Chennai AWS Training in Chennai Core Java Training in Chennai Javascript Training in ChennaiHibernate Training in ChennaiHTML5 Training in ChennaiPhotoshop Classes in ChennaiMobile Testing Training in ChennaiQTP Training in ChennaiLoadRunner Training in ChennaiDrupal Training in ChennaiManual Testing Training in ChennaiSpring Training in ChennaiStruts Training in ChennaiWordPress Training in ChennaiSAS Training in ChennaiClinical SAS Training in ChennaiBlue Prism Training in ChennaiMachine Learning course in ChennaiMicrosoft Azure Training in ChennaiUiPath Training in ChennaiMicrosoft Dynamics CRM Training in ChennaiUI UX Design course in ChennaiSalesforce Training in ChennaiVMware Training in ChennaiR Training in ChennaiAutomation Anywhere Training in ChennaiTally course in ChennaiReactJS Training in ChennaiCCNA course in ChennaiEthical Hacking course in ChennaiGST Training in ChennaiIELTS Coaching in ChennaiSpoken English Classes in ChennaiSpanish Classes in ChennaiJapanese Classes in ChennaiTOEFL Coaching in ChennaiFrench Classes in ChennaiInformatica Training in ChennaiInformatica MDM Training in ChennaiBig Data Analytics courses in ChennaiHadoop Admin Training in ChennaiBlockchain Training in ChennaiIonic Training in ChennaiIoT Training in ChennaiXamarin Training In ChennaiNode JS Training In ChennaiContent Writing Course in ChennaiAdvanced Excel Training In ChennaiCorporate Training in ChennaiEmbedded Training In ChennaiLinux Training In ChennaiOracle DBA Training In ChennaiPEGA Training In ChennaiPrimavera Training In ChennaiTableau Training In ChennaiSpark Training In ChennaiGraphic Design Courses in ChennaiAppium Training In ChennaiSoft Skills Training In ChennaiJMeter Training In ChennaiPower BI Training In ChennaiSocial Media Marketing Courses In ChennaiTalend Training in ChennaiHR Courses in ChennaiGoogle Cloud Training in ChennaiSQL Training In Chennai CCNP Training in Chennai PMP Training in Chennai OET Coaching Centre in Chennai

  • Are You Located in Any of these Areas

    Adyar, Adambakkam, Anna Salai, Ambattur, Ashok Nagar, Aminjikarai, Anna Nagar, Besant Nagar, Chromepet, Choolaimedu, Guindy, Egmore, K.K. Nagar, Kodambakkam, Koyambedu, Ekkattuthangal, Kilpauk, Meenambakkam, Medavakkam, Nandanam, Nungambakkam, Madipakkam, Teynampet, Nanganallur, Navalur, Mylapore, Pallavaram, Purasaiwakkam, OMR, Porur, Pallikaranai, Poonamallee, Perambur, Saidapet, Siruseri, St.Thomas Mount, Perungudi, T.Nagar, Sholinganallur, Triplicane, Thoraipakkam, Tambaram, Vadapalani, Valasaravakkam, Villivakkam, Thiruvanmiyur, West Mambalam, Velachery and Virugambakkam.

    FITA Velachery or T Nagar or Thoraipakkam OMR or Anna Nagar or Tambaram or Porur 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!