12 Essential Python Built‑in Functions Every Developer Should Master
Discover twelve powerful Python built‑in functions—from enumerate and zip to globals and locals—explained with clear examples, showing how they simplify indexing, pairing data, condition checks, sorting, mapping, filtering, and introspection, helping you write cleaner, more efficient code.
Python provides many powerful built‑in functions that can save time, reduce code complexity, and improve performance. These functions are often overlooked by beginners, who may unintentionally reinvent the wheel.
Below are the twelve Python built‑in functions I wish I had learned earlier!
1. enumerate() — Easy index tracking
When iterating over a list, you can use enumerate() to obtain both the index and the value without a manual counter.
cities = ['Paris', 'Tokyo', 'Cairo', 'Sydney']
for number, city in enumerate(cities, start=1):
print(number, city)Output:
1 Paris
2 Tokyo
3 Cairo
4 Sydney2. zip() — Easy data pairing
When you need to iterate over multiple lists simultaneously, zip() pairs the elements together.
books = ['1984', 'Dune', 'Hamlet']
authors = ['George Orwell', 'Frank Herbert', 'William Shakespeare']
for book, author in zip(books, authors):
print(f"'{book}' was written by {author}")Output:
'1984' was written by George Orwell
'Dune' was written by Frank Herbert
'Hamlet' was written by William Shakespeare3. any() and all() — Clear condition checks
any()returns True if at least one element of an iterable is true; all() returns True only if every element is true.
words = ["hello", "world", ""]
print(any(words)) # True (at least one non‑empty string)
print(all(words)) # False (because there is an empty string)This is much clearer than writing explicit loops for condition checking.
4. sorted() with key — One‑line custom sorting
You can perform custom sorting without writing complex logic by using sorted() with a key function.
products = [('Laptop', 1200), ('Phone', 800), ('Tablet', 600)]
sorted_products = sorted(products, key=lambda x: x[1]) # sort by price
print(sorted_products)Output:
[('Tablet', 600), ('Phone', 800), ('Laptop', 1200)]5. map() — Apply a function to each element
Instead of a for loop, map() applies a function to every item of an iterable.
nums = [1, 2, 3, 4, 5, 6]
doubled_evens = list(map(lambda x: x * 2 if x % 2 == 0 else x, nums))
print(doubled_evens)Output:
[1, 4, 3, 8, 5, 12]Alternatively, a list comprehension can be used:
nums = [1, 2, 3, 4, 5, 6]
cubed_odds = [x ** 3 for x in nums if x % 2 != 0]
print(cubed_odds) # [1, 27, 125]6. filter() — Extract elements that satisfy a condition
filter()keeps only the items that meet a given predicate.
words = ["apple", "banana", "orange", "grape", "umbrella"]
vowels = list(filter(lambda w: w[0].lower() in "aeiou", words))
print(vowels)Output:
['apple', 'orange', 'umbrella']7. reduce() — Accumulate values over an iterable
From the functools module, reduce() can perform cumulative operations such as finding the longest string.
from functools import reduce
words = ["python", "java", "javascript", "c"]
longest = reduce(lambda a, b: a if len(a) > len(b) else b, words)
print(longest)Output:
javascriptWhile sum() is more readable for numeric addition, reduce() shines for custom accumulation.
8. setdefault() — Get and set dictionary values simultaneously
setdefault()initializes a dictionary key if it does not exist, avoiding an explicit if key in dict check.
inventory = {'apples': 10}
bananas = inventory.setdefault('bananas', 5) # adds bananas if missing
print(inventory)Output:
{'apples': 10, 'bananas': 5}9. vars() — Inspect object attributes
vars()returns an object's __dict__, making it easy to view its attributes.
class Car:
def __init__(self, brand, year):
self.brand = brand
self.year = year
my_car = Car('Toyota', 2020)
print(vars(my_car))Output:
{'brand': 'Toyota', 'year': 2020}10. globals() and locals() — Inspect global and local variables
Use these functions to view variables in the current scope.
y = 5 # global variable
def my_function():
z = 15 # local variable
print("Inside function, locals():", locals())
print("Inside function, globals():", list(globals().keys())[:10])
my_function()Output (truncated):
Inside function, locals(): {'z': 15}
Inside function, globals(): ['y', 'my_function', '__name__', '__doc__', '__package__', ...]11. isinstance() — Pythonic type checking
isinstance()provides flexible type checking compared to using type().
data1 = "Hello"
data2 = [1, 2, 3]
print(isinstance(data1, str)) # True
print(isinstance(data2, (list, tuple))) # True
print(isinstance(data1, (list, tuple))) # FalseOutput:
True
True
False12. callable() — Check if an object can be called
Determine whether an object behaves like a function.
class Multiplier:
def __init__(self, factor):
self.factor = factor
def __call__(self, x):
return x * self.factor
double = Multiplier(2)
print(callable(double)) # True, because __call__ is defined
print(callable("hello")) # False, strings are not callableThis is especially useful when working with dynamically created objects.
Final Thoughts
These built‑in functions make my Python programming journey more efficient, productive, and enjoyable. Start using them now and you’ll be amazed by how much cleaner and faster your code becomes!
Did I miss any of your favorite built‑in functions? Let me know in the comments!
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Code Mala Tang
Read source code together, write articles together, and enjoy spicy hot pot together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
