How to Pass a List as an Argument to a Class in Python?

Estimated read time 2 min read

To pass a list as an argument to a class in Python, you can simply include the list as one of the parameters in the class constructor (also known as the __init__ method). Here’s an example:

class MyClass:
    def __init__(self, my_list):
        self.my_list = my_list

my_list = [1, 2, 3, 4]
my_object = MyClass(my_list)

In this example, we define a class called MyClass with a constructor that takes in one parameter, my_list. The constructor then assigns the my_list parameter to an instance variable called my_list.

We then create a list called my_list and pass it as an argument to the MyClass constructor when we create an object called my_object.

You can also pass the list as a keyword argument by specifying the parameter name:

class MyClass:
    def __init__(self, my_list):
        self.my_list = my_list

my_list = [1, 2, 3, 4]
my_object = MyClass(my_list=my_list)

In this example, we pass the my_list parameter as a keyword argument to the MyClass constructor by specifying the parameter name my_list=my_list.

Once the list has been passed as an argument to the class constructor, it can be accessed within the class through the instance variable that was assigned to it (in this case, self.my_list). For example, you could print the list from within the class like this:

class MyClass:
    def __init__(self, my_list):
        self.my_list = my_list
        print(self.my_list)

my_list = [1, 2, 3, 4]
my_object = MyClass(my_list)

This would output:

[1, 2, 3, 4]

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply