Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between a list & a stack in python?

Tags:

python

stack

list

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]
like image 749
payal Avatar asked Jul 14 '26 08:07

payal


1 Answers

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

See the Wikipedia explanation.

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.

You could also use the collections.deque() type; it is usually slightly faster than a list for the typical patterns seen when using either as a stack. However, like lists, a deque can be used for other purposes too.

like image 54
Martijn Pieters Avatar answered Jul 17 '26 20:07

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!