Skip to content

Python Objects and the dir() function

In Python we have the ability to associate a group of functions with any object class. These functions when grouped together with an object are called methods. You can think of them accessor methods go get access to the data or behavior of an object class.

For example, a dictionary object has the .items() method. So how do you know what methods are available to you? That's where the dir function comes in! Just pass whatever data or object you want to know about as an argument.




You can see this returns a list of methods, a lot of which begin and end with __, those are special methods that we won't worry about for the purposes of this lab. But the rest of them are methods we can use on a list object. For example, .pop().



print(last) #prints 4

print(my_list) #prints [1,2,3]

The pop() method will remove and return the last element from the list, that is if you call pop without passing in an argument, as we just did. Pop will accept one optional argument, that is can pass the index of the item you want to remove from the list and return. With lists we start counting indices from 0. So in the list below 1 is at the 0th index and 6 is at the 5th index.


print(my_list[0]) # prints 1

print(my_list[5]) # prints 6

print(my_list.pop(2)) # removes and prints 3

print(my_list) # prints [1,2,4,5,6]