20 Essential Python Built-in Functions Every Data Scientist Should Know
Python is one of the most popular programming languages for data science, thanks in large part to its simple syntax, powerful libraries, and versatile built-in functions. Built-in functions are pre-defined functions that come bundled with Python, providing essential functionality for various tasks without requiring you to import any external libraries.
As a data scientist, mastering Python‘s built-in functions will make you a more efficient and effective coder. In this article, we‘ll take an in-depth look at 20 of the most useful built-in functions for data science, with code examples and tips for usage. Let‘s dive in!
1. print()
The workhorse of Python output, print() displays the specified message to the console or other standard output. While it‘s not data science specific, print() is essential for examining variables and debugging code.
x = 10
print("The value of x is", x)
Output:
The value of x is 10
You can print multiple items by separating them with commas. print() will automatically add spaces between items and a newline character at the end.
2. type()
Returns the data type of an object. Knowing the types of your variables is crucial in data science, as different types have different properties and methods.
x = 10
word = "hello"
nums = [1, 2, 3]
print(type(x))
print(type(word))
print(type(nums))
Output:
<class ‘int‘> <class ‘str‘> <class ‘list‘>
Use type() to ensure your variables are the expected data types before performing operations on them.
3. input()
Requests and returns user input from the console. In data science projects, you might use this to allow users to specify parameters or file paths.
name = input("Enter your name: ")
print("Hello,", name)
Output:
Enter your name: John Hello, John
Remember that input() always returns a string. Use type conversion functions like int() or float() to convert the input if needed.
4. abs()
Returns the absolute value of a number. abs() is handy for ensuring values are positive or calculating distances between values.
x = -10
y = abs(x)
print(y)
Output:
10
abs() also works on complex numbers, returning the magnitude.
5. pow()
Raises a number to a power. This is useful for exponential calculations and regularization in machine learning.
x = pow(2, 3) # 2^3
print(x)
Output:
8
pow() can also compute modular exponentiation, which is helpful for cryptography and randomized algorithms.
6. dir()
Returns a list of valid attributes for an object. This is a great way to explore the properties and methods of Python objects.
nums = [1, 2, 3]
print(dir(nums))
Output:
[‘__add__‘, ‘__class__‘, ‘__contains__‘, ...]
Use dir() to discover what operations you can perform on an object.
7. sorted()
Returns a new sorted list from an iterable. Sorting is a common data preprocessing step in data science.
nums = [3, 1, 4, 1, 5, 9, 2, 6]
sorted_nums = sorted(nums)
print(sorted_nums)
Output:
[1, 1, 2, 3, 4, 5, 6, 9]
You can sort in descending order with the reverse parameter and specify a key function to sort by with the key parameter.
8. max()
Returns the largest item in an iterable or the largest of two or more arguments. Useful for finding top values in a dataset.
nums = [3, 1, 4, 1, 5, 9, 2, 6]
print(max(nums))
Output:
9
There‘s also a min() function that returns the smallest item.
9. round()
Rounds a number to a specified number of decimal places. Rounding is often necessary when presenting results.
x = 1.23456
print(round(x, 2))
Output:
1.23
If the second argument is omitted, round() will round to the nearest integer.
10. divmod()
Returns a tuple of the quotient and remainder when dividing two numbers. This can be more efficient than using separate division and modulo operations.
print(divmod(10, 3))
Output:
(3, 1)
divmod() is useful for generating sequences or implementing custom hashing algorithms.
11. id()
Returns the unique identifier of an object. This can be helpful for checking if two variables refer to the same object in memory.
x = [1, 2, 3]
y = [1, 2, 3]
print(id(x))
print(id(y))
print(id(x) == id(y))
Output:
140330060241024 140330060240960 False
Even though x and y have the same value, they are different objects in memory.
12. ord()
Returns the integer representing the Unicode code point of a character. This is useful for text processing and analysis.
print(ord(‘a‘))
print(ord(‘€‘))
Output:
97 8364
There‘s also a chr() function that returns the character for an integer code point.
13. len()
Returns the length (number of items) of an object. len() is essential for working with sequences like lists and strings.
nums = [1, 2, 3]
print(len(nums))
word = "hello"
print(len(word))
Output:
3 5
len() is often used in loops and conditional statements to process sequences.
14. sum()
Returns the sum of items in an iterable. sum() is handy for calculating totals and averages.
nums = [1, 2, 3, 4, 5]
print(sum(nums))
Output:
15
You can also specify a start value that‘s added to the sum:
print(sum(nums, 10))
Output:
25
15. help()
Invokes the built-in help system. You can use help() to get information on a function, module, or other object.
help(sum)
Output:
Help on built-in function sum in module builtins:sum(iterable, /, start=0) Return the sum of a ‘start‘ value (default: 0) plus an iterable of numbers
When the iterable is empty, return the start value. This function is intended specifically for use with numeric values and may reject non-numeric types.help() is great for quickly looking up how to use a function without leaving your Python environment.
16. isinstance()
Checks if an object is an instance of a specified class or data type. This is useful for validating inputs and handling different data types in your code.
x = 10 print(isinstance(x, int))y = "hello"
print(isinstance(y, str))print(isinstance(y, int))
Output:
True True Falseisinstance() can also check if an object is an instance of any of multiple types by passing a tuple of types.
17. map()
Applies a function to every item in an iterable and returns a map object with the results. map() is great for performing transformations on large datasets.
def square(x): return x ** 2nums = [1, 2, 3, 4, 5] squared_nums = list(map(square, nums)) print(squared_nums)
Output:
[1, 4, 9, 16, 25]map() is often used with lambda functions for concise one-line transformations.
18. filter()
Filters an iterable by applying a function that returns True or False to each item and returns an iterator with the items that returned True.
def is_even(x): return x % 2 == 0nums = [1, 2, 3, 4, 5] even_nums = list(filter(is_even, nums)) print(even_nums)
Output:
[2, 4]Like map(), filter() is often used with lambda functions for conciseness.
19. zip()
Takes two or more iterables and returns an iterator of tuples where the i-th tuple contains the i-th element from each of the argument iterables. zip() is useful for combining related datasets.
nums = [1, 2, 3] letters = [‘a‘, ‘b‘, ‘c‘] combined = list(zip(nums, letters)) print(combined)Output:
[(1, ‘a‘), (2, ‘b‘), (3, ‘c‘)]If the iterables are of different lengths, zip() will stop when the shortest iterable is exhausted.
20. enumerate()
Returns an iterator of tuples containing a count and the values from an iterable. This is handy for keeping track of the index when looping through a sequence.
letters = [‘a‘, ‘b‘, ‘c‘] for i, letter in enumerate(letters): print(i, letter)Output:
0 a 1 b 2 cBy default, enumerate() starts the count at 0, but you can specify a different start value.
Conclusion
Python‘s built-in functions are powerful tools that every data scientist should have in their toolkit. By mastering these 20 essential functions, you‘ll write cleaner, more efficient, and more readable code.
As you work on data science projects, try to incorporate these functions wherever applicable. With practice, you‘ll develop a keen sense for when and how to use each one.
Of course, this article only scratches the surface of Python‘s built-in functions. To learn more, check out the official Python documentation or dive into a good Python reference book. Happy coding!
This article was published as a part of the Data Science Blogathon