🤔Data $tructure in Python

Let's Learn what is Data Structure 

            A data structure is a data organization, management, and storage format that enables efficient access and modification. More precisely, a data structure is a collection of data values, the relationships among them, and the functions or operations that can be applied to the data.




Inbuilt Data Structures in Python 

            

Lists

    Lists are used to store data of different data types in a sequential manner. There are addresses assigned to every element of the list, which is called as Index. The index value starts from 0 and goes on until the last element called the positive index. There is also negative indexing which starts from -1 enabling you to access elements from the last to first. Let us now understand lists better with the help of an example program.

Tuple

    Tuples are the same as lists are with the exception that the data once entered into the tuple cannot be changed no matter what. The only exception is when the data inside the tuple is mutable, only then the tuple data can be changed. The example program will help you understand better.

Dictionary

    Dictionaries are used to store key-value pairs. To understand better, think of a phone directory where hundreds and thousands of names and their corresponding numbers have been added. Now the constant values here are Name and the Phone Numbers which are called as the keys. And the various names and phone numbers are the values that have been fed to the keys. If you access the values of the keys, you will obtain all the names and phone numbers. So that is what a key-value pair is. And in Python, this structure is stored using Dictionaries. 

Sets

    Sets are a collection of unordered elements that are unique. Meaning that even if the data is repeated more than one time, it would be entered into the set only once. It resembles the sets that you have learnt in arithmetic. The operations also are the same as is with the arithmetic sets. An example program would help you understand better.

lists FEATURES 

            Lists are ordered collection of heterogeneous elements(i.e, elements of different data types). 
            Lists are just like dynamic sized arrays, declared in other languages (vector in C++ and ArrayList in Java).
            Lists are Mutable.
            Lists are represented by pair of square braces []  .
            Lists allow duplicate values.
            The elements in a list are indexed according to a definite sequence and the indexing of a list is done with 0 being the first index.


Representation of lists:

        To create a list, we use the square brackets [] and add elements into it accordingly. If you do not pass any elements inside the square brackets, we get an empty list as the output.

LIST OPERATIONS 

        List creation:

    my_list = [] #create empty list
    print(my_list)
    my_list = [1, 2, 3, 'example', 3.132] #creating list with data
    print(my_list)

        Output:
            []
            [1, 2, 3, ‘example’, 3.132]

        Adding Elements

            Adding the elements in the list can be achieved using the append(), extend() and insert() functions.

    • The append() function adds all the elements passed to it as a single element.
    • The extend() function adds the elements one-by-one into the list.
    • The insert() function adds the element passed to the index value and increase the size of the list too.   
     1
2
3
4
5
6
7
8
my_list = [1, 2, 3]
print(my_list)
my_list.append([555, 12]) #add as a single element
print(my_list)
my_list.extend([234, 'more_example']) #add as different elements
print(my_list)
my_list.insert(1, 'insert_example') #add element i
print(my_list)

        Output:
            [1, 2, 3]
            [1, 2, 3, [555, 12]]
            [1, 2, 3, [555, 12], 234, ‘more_example’]
            [1, ‘insert_example’, 2, 3, [555, 12], 234, ‘more_example’]

        Deleting Elements

    • To delete elements, use the del keyword which is built-in into Python but this does not return anything back to us.
    • If you want the element back, you use the pop() function which takes the index value.
    • To remove an element by its value, you use the remove() function.

        Example:

      1
2
3
4
5
6
7
8
9
my_list = [1, 2, 3, 'example', 3.132, 10, 30]
del my_list[5] #delete element at index 5
print(my_list)
my_list.remove('example') #remove element with value
print(my_list)
a = my_list.pop(1) #pop element from list
print('Popped Element: ', a, ' List remaining: ', my_list)
my_list.clear() #empty the list
print(my_list)

        Output:
            [1, 2, 3, ‘example’, 3.132, 30]
            [1, 2, 3, 3.132, 30]
            Popped Element: 2 List remaining: [1, 3, 3.132, 30]
            []

        Accessing Elements

            Accessing elements is the same as accessing Strings in Python. You pass the index values and hence can obtain the values as needed.

    1
2
3
4
5
6
7
my_list = [1, 2, 3, 'example', 3.132, 10, 30]
for element in my_list: #access elements one by one
    print(element)
print(my_list) #access all elements
print(my_list[3]) #access index 3 element
print(my_list[0:2]) #access elements from 0 to 1 and exclude 2
print(my_list[::-1]) #access elements in reverse

        Output:
            1
            2
            3
            example
            3.132
            10
            30
            [1, 2, 3, ‘example’, 3.132, 10, 30]
            example
            [1, 2]
            [30, 10, 3.132, ‘example’, 3, 2, 1]

        Other Functions

            You have several other functions that can be used when working with lists.

    • The len() function returns to us the length of the list.
    • The index() function finds the index value of value passed where it has been encountered the first time.
    • The count() function finds the count of the value passed to it.
    • The sorted() and sort() functions do the same thing, that is to sort the values of the list. The sorted() has a return type whereas the sort() modifies the original list.
    1
2
3
4
5
6
7
my_list = [1, 2, 3, 10, 30, 10]
print(len(my_list)) #find length of list
print(my_list.index(10)) #find index of element that occurs first
print(my_list.count(10)) #find count of the element
print(sorted(my_list)) #print sorted list but not change original
my_list.sort(reverse=True) #sort original list
print(my_list)

        Output:

        6
        3
        2
        [1, 2, 3, 10, 10, 30]
        [30, 10, 10, 3, 2, 1]

TUPLE FEATURES 

            Tuple is an  Immutable array, ordered collection of heterogeneous elements
            It supports all data types
            Duplicate values are allowed in Tuples
            Indexing is supported by tuple,it starts from 0 and it allows negative indexing 
            Representation is ()
           Tuples are constant arrays

        TUPLE OPERATIONS: 

            Tuple Creation:

                 create a tuple using parenthesis or using the tuple() function.
        1
2
my_tuple = (1, 2, 3) #create tuple
print(my_tuple)

        Output:
            (1, 2, 3)

        Accessing Elements

            Accessing elements is the same as it is for accessing values in lists

        1
2
3
4
5
6
7
my_tuple2 = (1, 2, 3, 'enjoy') #access elements
for x in my_tuple2:
    print(x)
print(my_tuple2)
print(my_tuple2[0])
print(my_tuple2[:])
print(my_tuple2[3][4])

        Output:
        1
        2
        3
        enjoy
        (1, 2, 3, ‘enjoy’)
        1    
        (1, 2, 3, ‘enjoy’)
        e

        Appending Elements

        To append the values, you use the ‘+’ operator which will take another tuple to be appended to it.

    1
2
3
my_tuple = (1, 2, 3)
my_tuple = my_tuple + (4, 5, 6) #add elements
print(my_tuple)

        Output:
        ( 1, 2, 3, 4, 5, 6)

        Other Functions

        These functions are the same as they are for lists.

    1
2
3
4
5
my_tuple = (1, 2, 3, ['hindi', 'python'])
my_tuple[3][0] = 'english'
print(my_tuple)
print(my_tuple.count(2))
print(my_tuple.index(['english', 'python']))

        Output:
        (1, 2, 3, [‘english’, ‘python’])
        1
        3

Dictionary FEATURES  

        In Dictionary elements are stored as{key:value}
        It maintains Unordered collection of values
        Dictionaries are Mutable
        keys are unique
        Indexing is performed through keys
        They are implemented by hash tables --> data retrieval is fast, grown on demand

        Dictionary creation:

            
            Dictionaries can be created using the flower braces or using the dict() function. You need to add the key-value pairs whenever you work with dictionaries.
    1
2
3
4
my_dict = {} #empty dictionary
print(my_dict)
my_dict = {1: 'Python', 2: 'Java'} #dictionary with elements
print(my_dict)

        Output:
            {}
            { 1: ‘Python’, 2: ‘Java’}

        Changing and Adding key, value pairs

            To change the values of the dictionary, you need to do that using the keys. So, you firstly access the key and then change the value accordingly. To add values, you simply just add another key-value pair as shown below.

    1
2
3
4
5
6
my_dict = {'First': 'Python', 'Second': 'Java'}
print(my_dict)
my_dict['Second'] = 'C++' #changing element
print(my_dict)
my_dict['Third'] = 'Ruby' #adding key-value pair
print(my_dict)

        Output:
            {‘First’: ‘Python’, ‘Second’: ‘Java’}
            {‘First’: ‘Python’, ‘Second’: ‘C++’}
            {‘First’: ‘Python’, ‘Second’: ‘C++’, ‘Third’: ‘Ruby’}

        Deleting key, value pairs

    • To delete the values, you use the pop() function which returns the value that has been deleted.
    • To retrieve the key-value pair, you use the popitem() function which returns a tuple of the key and value.
    • To clear the entire dictionary, you use the clear() function.
            1
2
3
4
5
6
7
8
9
my_dict = {'First': 'Python', 'Second': 'Java', 'Third': 'Ruby'}
a = my_dict.pop('Third') #pop element
print('Value:', a)
print('Dictionary:', my_dict)
b = my_dict.popitem() #pop the key-value pair
print('Key, value pair:', b)
print('Dictionary', my_dict)
my_dict.clear() #empty dictionary
print('n', my_dict)

        Output:

            Value: Ruby
            Dictionary: {‘First’: ‘Python’, ‘Second’: ‘Java’}

            Key, value pair: (‘Second’, ‘Java’)
            Dictionary {‘First’: ‘Python’}

            {}

        Accessing Elements

         Access elements using the keys only. You can use either the get() function or just pass the key values and you will be retrieving the values.

1
2
3
my_dict = {'First': 'Python', 'Second': 'Java'}
print(my_dict['First']) #access elements using keys
print(my_dict.get('Second'))

        Output:
        Python
        Java

        Other Functions

         Different functions which return to us the keys or the values of the key-value pair accordingly to the keys(), values(), items() functions accordingly.

1
2
3
4
5
my_dict = {'First': 'Python', 'Second': 'Java', 'Third': 'Ruby'}
print(my_dict.keys()) #get keys
print(my_dict.values()) #get values
print(my_dict.items()) #get key-value pairs
print(my_dict.get('First'))

        Output:
        dict_keys([‘First’, ‘Second’, ‘Third’])
        dict_values([‘Python’, ‘Java’, ‘Ruby’])
        dict_items([(‘First’, ‘Python’), (‘Second’, ‘Java’), (‘Third’, ‘Ruby’)])
        Python


 SET FEATURES  


        
    Set is an unordered collection of data.

        No duplicates values are permitted

        No indexing

        Set is mutable

        We can perform all set theory operations

        Supports all data types

        Representation is {} with values separated by comma


        Creating a set

            Sets are created using the flower braces but instead of adding key-value pairs, you just pass values to it.

    1
2
my_set = {1, 2, 3, 4, 5, 5, 5} #create set
print(my_set)
        Output:
            {1, 2, 3, 4, 5}

        Adding elements

            To add elements, you use the add() function and pass the value to it. 

    1
2
3
my_set = {1, 2, 3}
my_set.add(4) #add element to set
print(my_set)

        Output:
           {1, 2, 3, 4}

        Operations in sets

            The different operations on set such as union, intersection and so on are shown below.

    1
2
3
4
5
6
7
8
my_set = {1, 2, 3, 4}
my_set_2 = {3, 4, 5, 6}
print(my_set.union(my_set_2), '----------', my_set | my_set_2)
print(my_set.intersection(my_set_2), '----------', my_set & my_set_2)
print(my_set.difference(my_set_2), '----------', my_set - my_set_2)
print(my_set.symmetric_difference(my_set_2), '----------', my_set ^ my_set_2)
my_set.clear()
print(my_set)

    • The union() function combines the data present in both sets.
    • The intersection() function finds the data present in both sets only.
    • The difference() function deletes the data present in both and outputs data present only in the set passed.
    • The symmetric_difference() does the same as the difference() function but outputs the data which is remaining in both sets.

        Output:

            {1, 2, 3, 4, 5, 6} ———- {1, 2, 3, 4, 5, 6}
            {3, 4} ———- {3, 4}
            {1, 2} ———- {1, 2}
            {1, 2, 5, 6} ———- {1, 2, 5, 6}
            set()

Comments