= ['apple', 'organge', 'pear']
fruits dir(fruits)
Most Useful Python Function for Beginners
As a graduate student, I’ve helped hundreds of students get started with Python. Most of the students I’ve helped are taking introductory computer science or scientific computing courses.
Again and again, when students get stuck with their programming homework, I have found one function rises above the rest in helping them dig their way out of the trenches.
Dir()
In my experience, students have a real eureka moment when they see the printout of the dir
function. Not only is it cool to see everything you can do with a given Python object, it also provides a nice segway into discussing object-oriented programming and what all those underscores mean. Now, I only became familiar with dir
because I’d often forget what methods were available for more obscure Python objects like lists (< insert joke here>). And really, that is how I frame this functions utility - it is great for when you forget how to do something like get the length of a list or dimensions of a numpy array.
Here is a simple example where we have a list of fruits and dir(fruits)
tells us the built-in list methods we can apply to our lists of fruits.
A slightly more advanced use case is numpy arrays. I’d also like to add, using dir
in combination with the help
function (applied to the np.array
here) makes for a great one-two-punch to troubleshoot code.
import numpy as np
= np.array([['apple', 'organge', 'pear'], ['banana', 'plum', 'mango']])
fruits dir(fruits)
help(np.array)