What is the purpose of the dir() function in Python?

Long Answer
Views 229

Answer:

The dir() function in Python is used to get a list of all the attributes (including methods) available in an object. It returns a list of strings, which can be useful for exploring an object's properties and methods.

Here's an example of using the dir() function in Python:


my_list = [1, 2, 3]
print(dir(my_list))
# ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', 
# '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', 
# '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', 
# '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', 
# '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', 
# '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 
# 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 
# 'reverse', 'sort']

In this example, the dir() function is used to get a list of all the attributes (including methods) available in the list my_list. The result shows the list of all the methods that can be used with the list object.

Related Articles:

This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of Python, click the links and dive deeper into this subject.

Join Our telegram group to ask Questions

Click below button to join our groups.