How would I create a custom list class in python?

print list of objects python
python class
python list
python list of class objects
how to initialize a list in a class python
python list of different classes
python extend list class
python list methods

I would like to write a custom list class in Python (let's call it MyCollection) where I can eventually call:

for x in myCollectionInstance:
    #do something here

How would I go about doing that? Is there some class I have to extend, or are there any functions I must override in order to do so?

Python Language Reference, §3.4.6, "Emulating container types"

Sure, you can play with the default argument value: class AB: def __init__(self, data=None): self.data = data if data is not None else [] def  Methods in objects are functions that belong to the object. Let us create a method in the Person class: Example. Insert a function that prints a greeting, and execute it on the p1 object: class Person: def __init__ (self, name, age): self.name = name. self.age = age. def myfunc (self):

Your can subclass list if your collection basically behaves like a list:

class MyCollection(list):
    def __init__(self, *args, **kwargs):
        super(MyCollection, self).__init__(args[0])

However, if your main wish is that your collection supports the iterator protocol, you just have to provide an __iter__ method:

class MyCollection(object):
    def __init__(self):
        self._data = [4, 8, 15, 16, 23, 42]

    def __iter__(self):
        for elem in self._data:
            yield elem

This allows you to iterate over any instance of MyCollection.

The UserList class (in the UserList module) provides a listlike base class that you can extend to suit your needs. UserList accepts a list to use as  I agree that default arguments can (and should) be used for the backing list of your class. In addition, consider inheriting from collections.abc.Sequence and delegating __getitem__ and __len__ to the backing list. (Add other list-like methods as necessary.) This will make sure your class acts as a well-behaved list-like.

I like to subclass MutableSequence, as recommended by Alex Martelli. This works well for me, particularly when I need to add custom methods on top of the list I'm building.

from collections import MutableSequence

class MyList(MutableSequence):
    """A container for manipulating lists of hosts"""
    def __init__(self, data=None):
        """Initialize the class"""
        super(MyList, self).__init__()
        if (data is not None):
            self._list = list(data)
        else:
            self._list = list()

    def __repr__(self):
        return "<{0} {1}>".format(self.__class__.__name__, self._list)

    def __len__(self):
        """List length"""
        return len(self._list)

    def __getitem__(self, ii):
        """Get a list item"""
        return self._list[ii]

    def __delitem__(self, ii):
        """Delete an item"""
        del self._list[ii]

    def __setitem__(self, ii, val):
        # optional: self._acl_check(val)
        self._list[ii] = val

    def __str__(self):
        return str(self._list)

    def insert(self, ii, val):
        # optional: self._acl_check(val)
        self._list.insert(ii, val)

    def append(self, val):
        self.insert(len(self._list), val)

if __name__=='__main__':
    foo = MyList([1,2,3,4,5])
    foo.append(6)
    print foo  # <MyList [1, 2, 3, 4, 5, 6]>

For details about making an iterable see Build a Basic Python Iterator Note that to iterate your object e.g. with for you don't need to convert it to a list but it  Create List Object Class in Python. It is a basic question. I am trying the following code: class SMS_store: def __init__(self): self= [] #probably something is wrong here def add_new_arrival(self,from_number,time_arrived,text_of_SMS): self.append( [False,from_number,time_arrived,text_of_SMS]) #append list to self list self[len(self)-1]=tuple(self[len(self)-1]) def message_count(self): return len(self) my_inbox=SMS_store() my_inbox.add_new_arrival('01234','9:37 AM','How are you?')

You could extend the list class:

class MyList(list):

    def __init__(self, *args):
        super(MyList, self).__init__(args[0])
        # Do something with the other args (and potentially kwars)

Example usage:

a = MyList((1,2,3), 35, 22)
print(a)
for x in a:
    print(x)

Expected output:

[1, 2, 3]
1
2
3

Call the class constructor for every element, then create a list containing each object instance. class number_object(object):. We can create list of object in Python by appending class instances to list. By this, every index in the list can point to instance attributes and methods of the class and can access them. By this, every index in the list can point to instance attributes and methods of the class and can access them.

In Python 3 we have beautiful collections.UserList([list]):

Class that simulates a list. The instance’s contents are kept in a regular list, which is accessible via the data attribute of UserList instances. The instance’s contents are initially set to a copy of list, defaulting to the empty list []. list can be any iterable, for example a real Python list or a UserList object.

In addition to supporting the methods and operations of mutable sequences, UserList instances provide the following attribute: data A real list object used to store the contents of the UserList class.

https://docs.python.org/3/library/collections.html#userlist-objects

Lets build a custom list class that will only accept integers and floats. If we attempt to append, any other data-type, lets say for arguments sake a  Python Module Search Path. While importing a module, Python looks at several places. Interpreter first looks for a built-in module. Then(if built-in module not found), Python looks into a list of directories defined in sys.path. The search is in this order. The current directory. PYTHONPATH (an environment variable with a list of directories).

Python provides full-fledged support for implementing your own data structure using classes and custom It consists of a list of arbitrary functions that can be applied to a collection of objects and produce a list of results. As, many houses can be made from a description, we can create many objects from a class. An object is also called an instance of a class and the process of creating this object is called instantiation. Defining a Class in Python. Like function definitions begin with the keyword def, in Python, we define a class using the keyword class.

It's very useful when implementing a list style object. Let's create our custom object, add an item to it, and try to get it. Classes — Python 3.8.3 documentation. 9. Classes ¶. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by its class) for modifying its state.

Instead, I could also create my own class that has a magiclist attribute but I would then have to create new methods for appending, extending, etc., if I want to get to the list using: magiclistobject.append() # instead of magiclistobject.list.append()

Comments
  • Could you clarify better your requirements? If you subclass any iterable class (list, dict, etc...) it should work without problems. But maybe I am missing something?
  • @mac: If I subclassed an iterable class, I'd also want a way to be able to access the underlying list object so that I can provide additional functions that act on it. I don't want a key-value pair (dict), so something that emulates an indexed collection (list) would suffice.
  • Not necessarily. for will also iterate from index 0 to until __getitem__() raises an exception; see the linked documentation for details.
  • I think the signature of your super method is wrong (only 99% sure, but doesn't list() accept only one iterable as argument? Also, is there a special reason for the final colon on the super call?
  • Yes, you are of course right, I edited to code. Thanks for the hint.
  • if not (data is None): that's not how you write your python code, until a Grand Jedi Master you are. if data is not None -- this looks good.
  • True, in addition, I guess only if data: should work fine.