1

I'm studying and practicing Python right now. I'm kinda scared by the concept of classes in it and I'm stuck wondering how to implement data structures like Linked Lists, Graphs and Trees.

I've heard from many that these are the most important data structures asked in interviews and coding competitions.

So my question is, Is there a way to implement all the said data structures without using classes and just by using predefined data structures like lists, dictionaries etc?

4
  • Since everything is an object and objects are instances of classes, you better get over that fear of classes of yours… Commented Oct 9, 2020 at 18:06
  • There is, but please. Just use classes. Commented Oct 9, 2020 at 18:06
  • 2
    Of course you can. You can implement data structures in assembler if you want. But you really need to learn about classes in Python. There is nothing to be scared of, especially if you are just trying to implement some data structures. It makes it easier not harder Commented Oct 9, 2020 at 18:08
  • "I've heard from many that these are the most important data structures asked in interviews and coding competitions." -- they also asks lots of questions from python classes and oop. So, learn it. :) Commented Oct 9, 2020 at 18:11

1 Answer 1

1

If we are being pedantic, everything in python is a class, so you can't avoid them. If you are concerned about everything that goes into creating your own class, like which methods should be defined where, that's something we can focus on. In fact, there is no general consensus on the boundaries to any given class and popular programs like C and Go don't even have them.

An alternative is to just use a dict to hold key/value pairs. Roughly, a class is just a dictionary with associated methods anyway. Dictionary keys can hold a wide variety of objects (as long as they are hashable) whereas class attributes must be strings and are further restricted to fit lexicographically in a program. A linked list for instance could be { "next object":obj, "previous object":obj, "item":obj } or even a list [obj, obj, obj] and your code remembers what those indexes are.

But classes are very convenient, especially when implementing other data structures. It makes sense that methods manipulating a linked list node would be on the node itself. There isn't much to gain avoiding classes when they are reasonable data structures to use.

There are plenty of modules out there that implemente linked lists, trees and graphs. Unless this is an exercise in learning data structures, some time spent with your favorite search engine is the best option of all.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.