Friday 2 July 2021

Python crash course (part 3): some collections and data structures - lists, queues and sets

Previosly: functions in Python

Today: Collections.

There are lot of useful collections implemented in Python.

The built-in elementary ones are lists (which allow access by index, so they act as arrays if needed; and they can also implement append() and pop(), making them LIFO stacks as well), sets, tuples and dictionaries. In this article we'll cover the first two (lists and sets) and also queues, although they're not a built-in type.

As usual, I won't elaborate much. Instead I'll show some code, which should quickly demonstrate basic concepts.

Lists

Let's begin with this code:

# !/usr/bin/python3

def main():
    # create and initialize a list:
    mylist = [369123]
    # show its contents:
    print(mylist)
    # -> [3, 6, 9, 12, 3]
    print(type(mylist))
    # -> <class 'list'>

    # get its length:
    print(len(mylist))
    # -> 5

    # access element by index
    # (change the 1st one to 6):
    mylist[0] = 6
    print(mylist)
    # -> [6, 6, 9, 12, 3]

    # removes 1st occurance:
    mylist.remove(6
    print(mylist)
    # -> [6, 9, 12, 3]

if __name__ == "__main__":
    main()


After each print call I've put result by in the following command (the result goes after # ->  )

As you can see, we can just print elements by calling print with a collection as parameter. You can also access list elements by index, making them 'arraylists'.

Lists as stacks

Please note the lists can be also uses as LIFO (stacks). We can add this code to the main() function:

    # appends in the end
    # (stack-like push):
    mylist.append(10)
    print(mylist)
    # -> [6, 6, 9, 12, 10]

    # stack.pop (LIFO):
    val = mylist.pop()
    print(val)
    # -> 10
    print(mylist)
    # -> [6, 6, 9, 12]

.. BTW lists don't have to include consistent-type elements:

    mylist.append("Frodo")

    print(mylist)
    # -> [6, 6, 9, 12, 'Frodo']

Queues

Although lists are LIFO-stacks, FIFO-queues are disctinct type, which has to be imported. So let's get to beginning of our script and change it that way:

# !/usr/bin/python3

from collections import deque

def main():

... so that we can add some queue-demonstrating code in the end:

    # queue (FIFO)

    # let's create a queue based on our list
    # (import needed for that!):

    mydeque = deque(mylist)
    print("myqueue:")
    print(mydeque)
    print(type(mydeque))
    # -> deque([6, 6, 9, 12, 'Frodo'])
    mydeque.appendleft(1# enqueue
    print(mydeque)
    # -> deque([1, 6, 6, 9, 12, 'Frodo'])
    print(mydeque.pop())
    # -> Frodo
    print(mydeque)
    # -> deque([1, 6, 6, 9, 12])

deque implements also append() method, which makes it behave like a stack in the previous examples.

Sets

The second collection inbuilt in Python (after lists, please not queues are not inbuilt) are sets. As in mathematics, the same element cannot be put in set twice (or rather: it can, but the second time is ignored). Also as in mathematics, set are unordered (no indexed access). An example (a whole new script this time):

# !/usr/bin/python3

def main():

    myset = {369123}
    print(myset)
    # -> {9, 3, 12, 6}
    # duplicates (3) are ignored

    print(type(myset))
    # -> <class 'set'>

    # you can't access a set by index
    # you can't change a set element 

    myset.remove(6)
    myset.add(15)
    print(myset)
    # -> {3, 9, 12, 15}


if __name__ == "__main__":
    main()

Please mind the syntax: while lists are initialized using square brackets [ ], sets use curly brackets { }.

In the next part we'll get to dictionaries and tuples.

No comments:

Post a Comment

Python crash course part 10: inheritance and polymorphism

In the last part we've shown how to create and use a class in Python. Today we're going to talk about inheritance: wchich means cre...