Python Data Structure

Introduction to Data Structure

Data structures are fundamental concepts of computer science which helps is writing efficient programs in any language. As you can see below following contents which will going to cover in this tutorial.
bvbgh
  • What are the Data Structures in Python and their types?

  • Data structures are a way of storing and organizing data efficiently. This will allow you to easily access and perform operations on the data.
    There is no one-size-fits-all kind of model when it comes to data structures. You will want to store data in different ways to store all types of data together, or you want something for faster searching of data, or maybe something that stores only distinct data items.
    Luckily, Python has a host of in-built data structures that help us to easily organize our data. Therefore, it becomes imperative to get acquainted with these first so that when we are dealing with data, we know exactly which data structure will solve our purpose effectively.
    The various data structures in computer science are divided four basic inbuilt data structures namely Lists, Dictionary, Tuple and Set. These almost cover 80% of the our real world data structures
    1: Lists in Python
    • Creating Lists
    • Accessing List elements
    • Appending values in Lists
    • Removing elements from Lists
    • Sorting Lists and Other functions
    • Concatenating Lists
    • List comprehensions
    • Stacks & Queues using Lists
    2: Tuples in Python
    • Creating Tuples in Python
    • Immutability of Tuples
    • Tuple assignment
    • Changing Tuples values
    • Remove item from the Tuple
    3: Dictionary in Python
    • Generating Dictionary
    • Accessing keys and values
    4: Sets in Python
    • Add and Remove elements from Sets
    • Sets Operations

1. Lists in Python

  • List is a collection data type in python. It is ordered and allows duplicate entries as well. The most versatile data structure.The lists are mutable in nature.
  • Lists in python need not be homogeneous, which means it can contain different data types like integers, strings and other collection data types. It is mutable in nature and allows indexing to access the members in a list.
  • To declare a list, we use the square brackets [].
  • List is like any other array that we declare in other programming languages.
  • Lists in python are often used to implement stacks and queues.
  • Therefore, the values can be changed even after a list is declared.

  • Creating Lists
  • Lists are created by enclosing elements within [square] brackets and each item is separated by a comma (,)
    >>> #creating a List
    >>> List=['python','codetech','shi']
    >>> print(type(List)) #this will print the type
    <class 'list'>
    >>> print(List)
    ['python', 'codetech', 'shi']
    Since each element in a list has its own distinct position, having duplicate values in a list is not a problem.
    >>> #creating a List with dublicate  value
    >>> List=['python','python','codetech','shi']
    >>> print(type(List)) #this will print the type
    <class 'list'>
    >>> print(List)
    ['python', 'python', 'codetech', 'shi']
    A list may have python list. You can print direct in python no need to use often print function in python.
    >>> list=['[python]','python','codetech','shi']
    >>> print(list)
    ['[python]', 'python', 'codetech', 'shi']
    >>> list
    ['[python]', 'python', 'codetech', 'shi']
    >>>

  • Accessing List elements
  • To access elements of a list, we use Indexing. Each element in a list has an index related to it depending on its position in the list. The first element of the list count as the index 0, the next element count as index 1, and so on. The last element of the list has an index of one less than the length of the list.
    Indexes don’t always have to be positive, they can be negative too.
    >>> #Accessing List elements
    >>> print(List[0])
    python
    >>> print(List[2])
    codetech						
    What do you think negative indexes indicate?
    While positive indexes return elements from the start of the list, negative indexes return values from the end of the list.
    This saves us from the trivial calculation which we would have to otherwise perform if we wanted to return the nth element from the end of the list.
    So instead of trying to return List_name[len(List_name)-1] element, we can simply write List_name[-1]. Using negative indexes, we can return the nth element from the end of the list easily. If we wanted to return the first element from the end, or the last index, the associated index is -1. Similarly, the index for the second last element will be -2, and so on.
    Remember, the 0th index will still refer to the very first element in the list.
    >>> # negative indexing
    >>> print(List[-1])
    shi
    >>> print(List[-2])
    codetech
    To return a range of elements between two positions in the lists is called Slicing. All we need to do is specify the start and end index within which we want to return all the elements – List_name[start : end].
    One important thing to remember here the element at the end index is never included. Only elements from start index till index equaling end-1 will be returned.
    >>> # Slicing the list
    >>> print(List[0:2])
    ['python', 'python']
    >>> print(List[0:3])
    ['python', 'python', 'codetech']

  • Appending values in Lists
  • 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()Adds an element to a specific position in the list which needs to be specified along with the value.
    >>> #append the list element
    >>> List.append(100)
    >>> List
    ['python', 'python', 'codetech', 'shi', 100]
    >>> #Extend the list element
    >>> List.extend([123, 'more_example']) #add as different elements
    >>> List
    ['python', 'python', 'codetech', 'shi', 100, 123, 'more_example']
    >>> #Insert element to the list
    >>> List.insert(1,'science')
    >>> List
    ['python', 'science', 'python', 'codetech', 'shi', 100, 123, 'more_example']
    

  • Removing elements from Lists
  • Removing elements from a list is as easy as adding them and can be done using the remove() or pop() methods:
    • remove() – Removes the first occurrence from the list that matches the given value
    • pop() – This is used when we want to remove an specified index element from the list. However, if we don’t provide an index value, the last element will be removed from the list.
    >>> # Remove element from list
    >>> #Our List
    >>> List
    ['python', 'science', 'python', 'codetech', 'shi', 100, 123, 'more_example']
    >>> #remove element fron list
    >>> List.remove('science')
    >>> List
    ['python', 'python', 'codetech', 'shi', 100, 123, 'more_example']
    >>> #pop element from index
    >>> List.pop(1)
    'python'
    >>> List
    ['python', 'codetech', 'shi', 100, 123, 'more_example']
    >>> #pop last elements from list
    >>> List.pop()
    'more_example'
    >>> List
    ['python', 'codetech', 'shi', 100, 123]
    >>> # to clear the list
    >>> List.clear() #empty the list
    >>> List
    []
    >>>

  • Sorting List and other Function
    • The method sort list elements in-place in either ascending or descending order:
      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.
    >>> #sorting list
    >>> mylist=[3,6,1,5,8,3]
    >>> #ascending order
    >>> mylist.sort()
    >>> mylist
    [1, 3, 3, 5, 6, 8]
    >>> #descending order
    >>> mylist.sort(reverse=True)
    >>> mylist
    [8, 6, 5, 3, 3, 1]
    
    • The len() function returns to us the length of the list.
    >>> #find length of list
    >>> Mylist=[3,6,1,5,8,3]
    >>> print(len(Mylist))
    6
    • The index() function finds the index value of value passed where it has been encountered the first time.
    >>> #find index of element that occurs first
    >>> print(Mylist.index(8))
    4
    >>> print(Mylist.index(6))
    1
    • The count() function finds the count of the value passed to it.
    >>> #find count of the element
    >>> mylist
    [8, 6, 5, 3, 3, 1]
    >>> print(mylist.count(3))
    2

  • Concatenating Lists
  • concatenatation method is use to concatenate two or more lists by simply using the (+) symbol. This will return a new list containing elements from both the lists
    >>> #concatenating lists
    >>> alist=['you','are']
    >>> blist=['going','to','be','fine']
    >>> clist=alist+blist
    >>> clist
    ['you', 'are', 'going', 'to', 'be', 'fine']
    

  • List comprehensions
  • List comprehension provides a neat way of creating new lists. These new lists are created by applying an operation on each element of an existing list. It will be easy to see their impact if we first check out how it can be done using the for-loops:
    >>> #for-loops
    >>> list=[1,2,3,4,5]
    >>> square=[]
    >>> for x in list:
    square.append(x**2)
    >>> square
    [1, 4, 9, 16, 25]
    >>> 
    >>>
    >>> #List comprehensions of upper code
    >>> list=[1,2,3,4,5]
    >>> square=[x**2 for x in list]
    >>> square
    [1, 4, 9, 16, 25]
    >>>

  • Stacks & Queues using Lists
  • A list is an in-built data structure in Python. But we can use it to create user-defined data structures.This two are very popular user-defined data structures built using lists are Stacks and Queues .
    Stacks are a list of elements in which the addition or deletion of elements is done from the end of the list. Think of it as a stack of books. Whenever you need to add or remove a book from the stack, you do it from the top. It uses the simple concept of (LIFO) Last-In-First-Out.
    >>> #Stack using in list
    >>> #1->2->3->4->5
    >>> stack=[1,2,3,4,5]
    >>> #1->2->3->4->5->6
    >>> stack.append(6)
    >>> stack
    [1, 2, 3, 4, 5, 6]
    >>> stack.pop()
    6
    >>> print(stack)
    [1, 2, 3, 4, 5]
    >>> stack.pop()
    5
    >>> print(stack)
    [1, 2, 3, 4]
    >>>
    Queues , on the other hand, are a list of elements in which the addition of elements takes place at the end of the list, but the deletion of elements takes place from the front of the list. You can think of it as a queue in the real-world. The queue becomes shorter when people from the front exit the queue. The queue becomes longer when someone new adds to the queue from the end. It uses the concept of (FIFO) First-In-First-Out.
    >>> #queue using in list
    >>> #1->2->3->4->5
    >>> queue=[1,2,3,4,5]
    >>> #1->2->3->4->5->6
    >>> queue.append(6)
    >>> print(queue)
    [1, 2, 3, 4, 5, 6]
    >>> queue.pop(0)
    1
    >>> print(queue)
    [2, 3, 4, 5, 6]
    >>>

    2: Tuples in Python

    • Tuples are another very popular in-built data structure in Python. Tuple is a collection of objects which unchangeable and immutable. It is ordered and the values can be accessed using the index values.
    • A tuple can have duplicate values as well. To declare a tuple, we use the parenthesis ( ).
    • These are quite similar to Lists except for one difference – they are immutable.
    • This means that once a tuple is created, cannot be modify. Tuples use parentheses ( ), whereas Lists use square brackets [ ].
    • Optionally you can put these comma-separated values between parentheses also.

  • Creating Tuples in Python
  • Tuples can be created by writing values within (parentheses) and each element is separated by a comma. But even if you write a bunch of values without any parenthesis and assign them to a variable, you will still end up with a tuple! Have a look for yourself:
    >>> #creating tuples
    >>> t=(4,2,'shi','code')
    >>> print(type(t)) # print type
    <class 'tuple'>
    >>> print(t)
    (4, 2, 'shi', 'code')
    >>> t1='calm',2,'nice'
    >>> print(t1)
    ('calm', 2, 'nice')
    >>>

  • Immutability of Tuples
    • Anything that cannot be modified after creation is immutable in Python.
    • Python language can be broken down into mutable and immutable objects.
    • Lists, dictionaries, sets are mutable objects (we will be exploring these in the further sections), meaning they can be modified after creation. On the other hand integers, floating values, boolean values, strings, and even tuples are immutable objects.
    • But what makes them immutable?
    • Everything in Python is an object. So we can use the in-built id() method which gives us the ability to check the memory location of an object.
    • This is known as the identity of the object. Let’s create a list and determine the location of the list and its elements:
    >>> mylist=[1,2,3,4,5]
    >>> #list location
    >>> print(id(mylist))
    1831981468224
    >>> #value location
    >>> print(id(mylist[0]))
    1831940221232
    >>>
    As you can see, both the list and its element have different locations in memory.
    Since we know lists are mutable, we can alter the value of elements.
    Let’s do that and see how it affects the location values:
    >>> mylist[0]=10
    >>> #list location
    >>> print(id(mylist))
    1831981468224
    >>> #value location
    >>> print(id(mylist[0]))
    1831940221520
    >>>
    As you can see, The location of the list did not change but the element did. This means that a new object was created for the element and saved in the list. This is what mutable is. A mutable object is able to change its state, or contents, after creation but an immutable object is not able to do that.
    But we can call tuples pseudo-immutable because even though they are immutable, they can contain mutable objects whose values can be modified!
    >>> mytuple=(1,2,3,[11,4,2])
    >>> #tuple location
    >>> print(id(mytuple))
    1831980890208
    >>> #value location
    >>> print(id(mytuple[-1]))
    1831981537344
    >>> 
    ------------------------------
    >>> #immutability of tuple
    >>> mytuple[-1].append(12)
    >>> #tuple location
    >>> print(id(mytuple))
    1831980890208
    >>> #value location
    >>> print(id(mytuple[-1]))
    1831981537344
    >>> print(mytuple)
    (1, 2, 3, [11, 4, 2, 12])
    >>> #In above example, we were able to change the values of an immutable object, list, contained within a tuple.

  • Tuple assignment
  • Tuple assignment are use for packing and unpacking the operations that you can perform to assign values to a tuple of elements from another tuple in a single line.
    We already saw tuple packing when we made our 't' tuple. Tuple unpacking is just the opposite-assigning values to variables from a tuple.
    >>> #tuple packing
    >>> t=('shi','py','code')
    >>> #tuple unpacking
    >>> a,b,c =t #sme as ->(a,b,c)=t
    >>> print(a)
    shi
    >>> print(b)
    py
    >>> print(c)
    code
    >>>
    It is very useful for swapping values in a single line.
    Honestly, this was one of the first things that got me excited about Python, being able to do so much with such little coding!
    >>> #imaginary tuples
    >>> a,b=10,20
    >>> b,a=a,b   #imaginary tuples
    >>> print(a)
    20
    >>> print(b)
    10
    >>>

  • Changing Tuple values
  • As we have seen that tuple values cannot be changed, you can actually make changes to it by converting it to a list using list(). And when you are done making the changes, you can again convert it back to a tuple using tuple().
    • we have a Tuple. Following is the step by step process of what we shall do to the Tuple.
    • We shall convert the tuple to a list.
    • Update the required item of the list.
    • Convert the list back to tuple and assign it to the original tuple.
    tuple1 = ('shi',3, 'python', 8, 4, 4)
    #change tuple to list
    list1 = list(tuple1)
    #update list
    list1[2] = 63
    #change back list to tuple
    tuple1 = tuple(list1)
    print(tuple1)
    output-('shi', 3, 63, 8, 4, 4)

  • Remove item from the Tuple
    • we will going to remove an item from the tuple, again using List.
    tuple1 = ('shi',3, 'python', 8, 4, 4)
    #change tuple to list
    list1 = list(tuple1)
    #remove an item from list
    list1.remove(8)
    #change back list to tuple
    tuple1 = tuple(list1)
    print(tuple1)
    output-('shi', 3, 'python', 4, 4)

    3: Dictionary in Python

    Dictionary is a collection of key:value pairs.

    Leave a Comment

    Your email address will not be published. Required fields are marked *

    This site uses Akismet to reduce spam. Learn how your comment data is processed.

    Shopping Cart