A Guided Tour of Python's Built-in Magic
Python
Python comes with a treasure chest of “built-in” functions that are available to you at all times, without needing to import anything. Mastering these functions is a key step toward writing clean, efficient, and “Pythonic” code.
Let’s go on a guided tour of some of the most useful and powerful ones!
Iteration & Collections
These functions are your best friends when working with lists, tuples, and other iterables.
enumerate()
Adds a counter to an iterable. Instead of managing an index manually, enumerate gives you both the index and the item.
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# Output:
# 0: apple
# 1: banana
# 2: cherry
zip()
Combines multiple iterables into a single iterator of tuples. It stops when the shortest iterable is exhausted.
students = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]
for student, score in zip(students, scores):
print(f"{student}'s score is {score}")
# Output:
# Alice's score is 85
# Bob's score is 92
# Charlie's score is 78
map()
Applies a function to every item of an iterable and returns a map object (which you can convert to a list).
numbers = [1, 2, 3, 4]
squared = map(lambda x: x**2, numbers)
print(list(squared)) # Output: [1, 4, 9, 16]
filter()
Filters an iterable by keeping only the items that return True for a given function.
numbers = [1, 2, 3, 4, 5, 6]
evens = filter(lambda x: x % 2 == 0, numbers)
print(list(evens)) # Output: [2, 4, 6]
sorted()
Returns a new sorted list from the items in an iterable.
numbers = [3, 1, 4, 1, 5, 9, 2]
print(sorted(numbers)) # Output: [1, 1, 2, 3, 4, 5, 9]
print(sorted(numbers, reverse=True)) # Output: [9, 5, 4, 3, 2, 1, 1]
Math & Numbers
Quick and easy functions for common mathematical operations.
sum()
Calculates the sum of all items in an iterable.
numbers = [10, 20, 30]
print(sum(numbers)) # Output: 60
max() & min()
Find the largest and smallest items in an iterable.
numbers = [10, 5, 25, 15]
print(max(numbers)) # Output: 25
print(min(numbers)) # Output: 5
abs()
Returns the absolute value of a number.
print(abs(-42)) # Output: 42
round()
Rounds a number to a given precision in decimal digits.
print(round(3.14159, 2)) # Output: 3.14
Type Conversion
Functions to convert data from one type to another.
# str(), int(), float()
num_str = "123"
num_int = int(num_str) # 123 (integer)
num_float = float(num_str) # 123.0 (float)
# list(), tuple(), set(), dict()
my_tuple = (1, 2, 3)
my_list = list(my_tuple) # [1, 2, 3]
my_list_with_dupes = [1, 2, 2, 3]
my_set = set(my_list_with_dupes) # {1, 2, 3} (duplicates removed)
Object Introspection & I/O
Functions for inspecting objects and handling basic input/output.
len()
Returns the number of items in an object.
my_list = [1, 2, 3, 4]
print(len(my_list)) # Output: 4
type()
Returns the type of an object.
print(type(123)) # Output: <class 'int'>
print(type("hello")) # Output: <class 'str'>
isinstance()
Checks if an object is an instance of a class.
if isinstance("hello", str):
print("It's a string!")
print() & input()
The most fundamental I/O functions. print() displays output to the console, and input() reads a line of text from the user.
print("Hello, world!")
name = input("What's your name? ")
print(f"Hello, {name}!")
Conclusion
This is just a glimpse into the world of Python’s built-in functions. By familiarizing yourself with them, you can solve common problems more elegantly and write code that is both more readable and more efficient. Dive in and explore!
Latest Posts
How Does React's useContext Really Work?
Explore the mechanics behind the useContext hook and the Context API. Learn how it solves prop drilling through a provider model and a subscription-based system.
Optimizing Docker Images for Production: Best Practices
Learn best practices for creating efficient, secure, and small Docker images for production environments, covering multi-stage builds, minimal base images, and more.
A Developer's Guide to Setting Up Docker on Linux
Learn how to install and configure Docker on your Linux machine to streamline your development workflow. A step-by-step guide for developers.
Enjoyed this article? Follow me on X for more content and updates!
Follow @Ctrixdev