Difference between a list & a stack in python?
Question: What is the difference between a list & a stack in python?

I have read its explanation in the python documentation but there both the
things seems to be same?

    
    
    >>> 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]
    


Answer: A stack is a _data structure concept_. The documentation uses a Python `list`
object to implement one. That's why that section of the tutorial is named
_Using Lists as Stacks_.

Stacks are just things you add stuff to, and when you take stuff away from a
stack again, you do so in reverse order, first in, last out style. Like a
stack of books or hats or... _beer crates_ :

[![beer crate
stacking](http://i.stack.imgur.com/9jJBd.jpg)](https://www.youtube.com/watch?v=9SReWtHt68A)

See the [Wikipedia
explanation](https://en.wikipedia.org/wiki/Stack_\(abstract_data_type\)).

Lists on the other hand are far more versatile, you can add and remove
elements anywhere in the list. You wouldn't try that with a stack of beer
crates with someone on top!

You could implement a stack with a custom class:

    
    
    from collections import namedtuple
    
    class _Entry(namedtuple('_Entry', 'value next')):
        def _repr_assist(self, postfix):
            r = repr(self.value) + postfix
            if self.next is not None:
                return self.next._repr_assist(', ' + r)
            return r
    
    class Stack(object):
        def __init__(self):
            self.top = None
        def push(self, value):
            self.top = _Entry(value, self.top)
        def pop(self):
            if self.top is None:
                raise ValueError("Can't pop from an empty stack")
            res, self.top = self.top.value, self.top.next
            return res
        def __repr__(self):
            if self.top is None: return '[]'
            return '[' + self.top._repr_assist(']')
    

Hardly a list in sight (somewhat artificially), but it is definitely a stack:

    
    
    >>> stack = Stack()
    >>> stack.push(3)
    >>> stack.push(4)
    >>> stack.push(5)
    >>> stack
    [3, 4, 5]
    >>> stack.pop()
    5
    >>> stack.push(6)
    >>> stack
    [3, 4, 6]
    >>> stack.pop()
    6
    >>> stack.pop()
    4
    >>> stack.pop()
    3
    >>> stack
    []
    

The Python standard library doesn't come with a specific stack datatype; a
`list` object does just fine. Just limit any use to `list.append()` and
`list.pop()` (the latter with no arguments) to treat a list _as_ a stack.

