0

I'm trying to create a list object that stores and sort either integer or string, but the input could also be a list i.e I would like to create it with a = SortedList(5) or a = SortedList([7, 5, 8])

class SortedList:

    def __init__(self, element):

        self.list = []

        if type(element) == "int" or type(element) == "str":
            self.list = self.list +[element]

        if type(element) == "list":
            self.list = self.list + element

        self.list.sort()

When my object is instantiate all I get is my empty list, my if statement is not taken into account. Any ideas please ?

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
  • Python != Javascript. you are checking the type against a string, but you need to use a type object, so `type(element) is int`. As an aside, please always tag any python related question with the generic [python] tag. At this point, Python 3 is pretty much assumed to be the case (python 2 is rapidly approaching it's end of life) – juanpa.arrivillaga Aug 14 '19 at 18:43
  • 1
    Take the fact that you cannot define a singleton list with `list(3)` as a *huge* hint that you should not do this at all. – chepner Aug 14 '19 at 18:56

1 Answers1

1

You have a problem with type comparison. You should compare it to int, str and list types, not to "int", "str" and "list" strings.

Here's the quick fix for your issue:

class SortedList:
    def __init__(self, element):

        self.list = []
        if type(element) == int or type(element) == str:
            self.list = self.list + [element]

        if type(element) == list:
            self.list = self.list + element

        self.list.sort()


a = SortedList(5)
b = SortedList([7, 5, 8])

print(a.list)
print(b.list)

Some things you could probably do better:

  1. Avoid using list as a variable name. You may accidentally override Python's built-in list type.
  2. Use isinstance for type comparison instead of type(...) == ...
  3. isinstance can accept a tuple of classes to compare against

So here's the reformatted program:

    class SortedList:
        def __init__(self, element):

            self.vals = []
            if isinstance(element, (int, str)):
                self.vals = self.vals + [element]

            if isinstance(element, list):
                self.vals = self.vals + element

            self.vals.sort()


    a = SortedList(5)
    b = SortedList([7, 5, 8])

    print(a.vals)
    print(b.vals)

Going even further,

  1. You could simplify the code by converting it to a list, if it is not a list, and processing further.
  2. Put a validation in place to ensure all data supplied as arguments are either integers or strings.

    class SortedList:
        def __init__(self, element):
            self.vals = element if isinstance(element, list) else [element]  # Convert to list if not a list
    
            if not all(isinstance(item, (int, str)) for item in self.vals):  # Ensure all items are either ints or strings
                raise TypeError("Incorrect Item Datatypes")
    
            self.vals.sort()
    
    a = SortedList(5)
    b = SortedList([7, 5, 8])
    
    print(a.vals)
    print(b.vals)
    

Now, assigning invalid data will throw an error:

    c = SortedList([7.0, 5, 8])

    Traceback (most recent call last):
        File "tester.py", line 16, in <module>
            c = SortedList([7.0, 5, 8])
        File "tester.py", line 6, in __init__
            raise TypeError("Incorrect Item Datatypes")
        TypeError: Incorrect Item Datatypes
Subhash
  • 3,121
  • 1
  • 19
  • 25
  • https://docs.python.org/3/library/functions.html#isinstance – wwii Aug 14 '19 at 18:48
  • 1
    It would be better to use `isinstance()` i.o `type()` as it is the recommended way to do such checks, especially as the question is a beginner question – bagerard Aug 14 '19 at 18:49
  • Elaborated to explain more concepts and how you could code better. Please accept answer is you it solved your problem :) – Subhash Aug 14 '19 at 19:03