1.1 List of Popular Built-in Functions
We've already encountered a bunch of built-in functions, but I want to talk about a few more that you'll find useful soon:
id()
hash()
dir()
Here's a bit more about them:
The id()
function
The id()
function returns a unique identifier for an object (a number). This identifier is an integer and remains unique for the object during its lifetime. It usually corresponds to the object's memory address, though Python's specification doesn't guarantee this.
You can use the unique object identifier to get a better understanding of operations, like where objects are duplicated versus where we have references to the same object. Identical objects will have different identifiers, but references to the same object will show the same identifier.
It can be useful during debugging to understand how Python manages objects in memory.
a = [1, 2, 3]
b = a
print(id(a)) # Prints the identifier for object 'a'
print(id(b)) # Prints the same identifier, since 'b' refers to the same object
The hash()
function
The hash()
function returns a hash value (a number) for the specified object, if it's hashable. Hashable objects in Python must be immutable and have a constant hash value during their lifetime.
Examples of such objects include numbers, strings, and tuples (if all their elements are also hashable). Hash values are used in dictionaries and sets for quick lookups. They're used to optimize searches and data storage where quick checks for equality and uniqueness are necessary.
print(hash("hello")) # Returns the hash value for the string "hello"
print(hash(42)) # Returns the hash value for the number 42
print(hash((1, 2, 3))) # Returns the hash value for the tuple (1, 2, 3)
Important!
The hash values of immutable objects remain constant during their lifetime. However, mutable objects like lists and dictionaries aren't hashable and can't be used as dictionary keys or set elements.
The dir()
function
The dir()
function returns a list of attributes and methods of an object. If no object is specified, dir()
returns a list of names in the current local scope. This function is useful for exploring the structure of objects and their attributes.
It's used to get a list of all the attributes and methods of an object, helping to better understand its structure and available functions. Often used for debugging and exploring objects, especially when documentation is limited or unavailable.
class MyClass:
def __init__(self):
self.name = "Alice"
def greet(self):
print("Hello, " + self.name)
obj = MyClass()
print(dir(obj)) # Prints the list of attributes and methods of the object 'obj'
print(dir()) # Prints the list of names in the current local scope
1.2 Working with Collections
There are a few more handy functions for working with collections. They might have been mentioned in earlier lectures, but let's dive a bit deeper into them now.
zip()
min()
max()
sum()
count()
The zip()
function
The zip()
function combines multiple iterable objects (like lists, tuples, strings) and returns an iterator of tuples. Each tuple contains elements gathered from the same index positions from all iterables.
It's often used to combine data from multiple iterables, allowing easy iteration over them simultaneously. It's also handy for creating dictionaries from two lists — one for keys, the other for values.
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
combined = zip(names, ages)
print(list(combined)) # Output: [('Alice', 25), ('Bob', 30), ('Charlie', 35)]
The max()
function
The max()
function returns the largest element from the passed iterable or from multiple passed arguments. You can also specify a key function to determine the comparison rule.
numbers = [1, 2, 3, 4, 5]
print(max(numbers)) # Output: 5
# With a key function
words = ["apple", "banana", "cherry"]
print(max(words, key=len)) # Output: 'banana'
The min()
function
The min()
function returns the smallest element from the passed iterable or from multiple passed arguments. You can also specify a key function to determine the comparison rule.
numbers = [1, 2, 3, 4, 5]
print(min(numbers)) # Output: 1
# With a key function
words = ["apple", "banana", "cherry"]
print(min(words, key=len)) # Output: 'apple'
The count()
function
The count()
function is used to count the number of occurrences of an element in an iterable object, such as a list or string. It's called on a list, collection, or iterator.
numbers = [1, 2, 2, 3, 4, 2, 5]
print(numbers.count(2)) # Output: 3
text = "hello world"
print(text.count("o")) # Output: 2
The sum()
function
The sum()
function returns the sum of all elements in an iterable object. Optionally, you can specify a starting value that will be added to the sum.
numbers = [1, 2, 3, 4, 5]
print(sum(numbers)) # Output: 15
# With a starting value
print(sum(numbers, 10)) # Output: 25
1.3 Executing Code
And here are two more functions that might be useful to you as a newbie:
eval()
exec()
They have powerful capabilities but require careful use due to potential security risks. Here's detailed info about each of these functions:
The eval()
function
The eval(expression)
function takes a string and evaluates it as a Python expression. It returns the result of executing this expression. It's used to compute string expressions as Python code.
Examples:
x = 10
result = eval("x + 5")
print(result) # Output: 15
The exec()
function
The exec()
function takes a string and executes it as Python code. Unlike eval()
, which only evaluates expressions, exec()
can execute any Python statements, including function definitions, loops, and module imports. This function doesn't return a value.
It's used for executing dynamic scripts and defining new functions or classes during program execution.
code = """
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
"""
exec(code)
# Output: Hello, Alice!
Important!
Like eval()
, exec()
can be dangerous when used with untrusted input. Be careful and avoid using exec()
for executing code in production.
GO TO FULL VERSION