Difference between a list & a stack in python? -


what difference between list & stack in python?

i have read explanation in python documentation there both things seems 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] 

a stack data structure concept. documentation uses python list object implement one. that's why section of tutorial named using lists stacks.

stacks things add stuff to, , when take stuff away stack again, in reverse order, first in, last out style. stack of books or hats or... beer crates:

beer crate stacking

see wikipedia explanation.

lists on other hand far more versatile, can add , remove elements anywhere in list. wouldn't try stack of beer crates on top!

you implement stack 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 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 none:             raise valueerror("can't pop empty stack")         res, self.top = self.top.value, self.top.next         return res     def __repr__(self):         if self.top none: return '[]'         return '[' + self.top._repr_assist(']') 

hardly list in sight (somewhat artificially), 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 specific stack datatype; list object fine. limit use list.append() , list.pop() (the latter no arguments) treat list as stack.


Comments