Block 9: Using help(), dir() & Reading Docs
Become confident exploring Python from the inside.
Concepts
- help(obj) for full documentation
- dir(obj) to list attributes/methods
- Reading docs.python.org and docstrings
- type() and isinstance() for type checking
Code Examples
help() and dir()
lst = [1, 2, 3]
print(dir(lst))
# help(lst.append)
type() and isinstance()
x = 42
y = 'hello'
print(type(x), type(y))
print(isinstance(x, int))
print(isinstance(y, str))
Exercise
Use help() on len, list.sort, str.split. Write a 1-line note + example for each. Use dir([]) to find and test 3 list methods you haven't used yet.
Solution
# help(len) - returns length of object
print(len([1,2,3]))
# help(list.sort) - sorts in place
lst = [3,1,2]; lst.sort(); print(lst)
# help(str.split) - splits by delimiter
print('a,b,c'.split(','))
# dir([]) reveals: copy, count, extend, index, reverse...
lst = [1,2,2,3]
print(lst.count(2))
print(lst.index(3))Practice Problems
Problem 1: Use isinstance(x, int) to check if x is an integer. Test with x=5 and x=5.0
Hint: isinstance(5, int) vs isinstance(5.0, int)
Problem 2: What does dir(str) show? Pick one method and use help() on it.
Hint: Try str.upper or str.strip
Application
You never need to memorize everything—help() and docs are your best friends when exploring new libraries.
Case Study
A developer encounters pd.merge() for the first time. They run help(pd.merge) and instantly see parameters: left, right, how, on.
Homework
Find the signature and behavior of str.join() from the docs and write a practical example.