In the
previous post, we have seen the methods of list data structure. In this post, let
us see how list can easily be used as stack and queue and also how to perform
deletion operation on lists and list
items.
Using list
as a stack:
Stack is a
data structure which works on the principle of “last in first out”
The List
methods make it very easy for us to use list as a stack.
There are only two
methods used to perform the stack operations of push and pop.
The first
method is list.apped().
This method
inserts an element at the end of the list. This is similar to “push” operation.
The pop
operation is performed using the list.pop() method.
This method
pops the element from the top of the stack.
In this way,
python lists can be easily implemented as stack.
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
Using List
as Queues:
Queue is a
data structure which works on the principle of “first in first out” .It is also
possible to use list as a queue, where the first element added is the first
element removed.
However lists are not efficient for this purpose. This is
because whenever queue and dequeue operations are performed, the elements have
to be shifted by one unit. This is not efficient as it consumes an extra cycle.
For that
reason, we have to import a class “deque” which is present in the “collections”
package . Collections.deque was specifically designed to perform queue
operations on lists.
The
following example gives a clear description of how to use list as a queue in
python.
>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry") # Terry arrives
>>> queue.append("Graham") # Graham arrives
>>> queue.popleft() # The first to arrive now leaves
'Eric'
>>> queue.popleft() # The second to arrive now leaves
'John'
>>> queue # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])
The “del”
statement:
There is a
way to remove an item form a list given its index value. This operation is
performed using the “del” statement.
This statement can be used to remove an
item from a list , slice a list (removing some portion of a list) and also to
remove the entire list.
Difference
between pop() and del :
The
difference between the pop() method and the del statement is that the pop()
method removes the element and returns the removed element whereas the del
statement simply removes the specified item without returning them.
The del
statement can also be used to delete variables. Once an element is deleted, further
accessing of that deleted variable results in an error.
>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.25, 1234.5]
>>> del a[:]
>>> a
[]