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
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:
.. BTW lists don't have to include consistent-type elements:
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:
... so that we can add some queue-demonstrating code in the end:
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):
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