Reputation:
I am learning about data structures and had a question. In textbook I am reading they show an implementation of a stack like this :
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
I do not get the need for creating a whole new class ? Why cant they just create a stack as such :
myStack = []
>>> myStack.append('a')
>>> myStack.append('b')
>>> myStack.append('c')
>>> myStack
['a', 'b', 'c']
>>> myStack.pop()
'c'
>>> myStack.pop()
'b'
>>> myStack.pop()
'a'
Is it faster or more versatile? I want to understand the difference so I am able to make decisions about how to implement one when needed.
Thank you!
Upvotes: 0
Views: 334
Reputation: 44838
A built-in data structure (like list
) will almost always be faster than anything written in Python. And this implementation of Stack
uses a list as the stack anyway, so it just adds additional overhead then.
If a data structure is not built into Python and is not provided by the standard library, then you'll have to create a class. You can create a class if the built-in data structure doesn't provide the methods you need (like peek
) as well.
Upvotes: 0
Reputation: 36033
This is just a basic example to give you a feel for how to implement your own data structure. A list is already good enough to use as a stack, but for more complicated data structures there won't be anything built in that works so well.
Upvotes: 1