LESSER-KNOWN YET POWERFUL FEATURES AND FUNCTIONS
Unlocking Python’s Hidden Gems: 60 Code Snippets to Elevate Your Coding Skills
Dive into the Depths of Python’s Lesser-Known Features and Functions for Next-Level Programming Mastery
In this comprehensive exploration, we delve into 60 of these lesser-known Python gems, each capable of adding a new dimension to your coding toolkit. From optimizing data structures to streamlining algorithms, and enhancing readability to boosting performance, these snippets are more than just code — they’re keys to unlocking Python’s full potential.
1. else
clause on loops: You can use an else
block with a for
or while
loop. It runs if the loop completes normally (without hitting a break
statement).
for i in range(3):
print(i)
else:
print("Loop finished normally")
2. enumerate
function: This function adds a counter to an iterable and returns it.
for index, value in enumerate(['a', 'b', 'c']):
print(f"{index}: {value}")
3. List comprehensions with if
clause: You can filter items in a list comprehension.
even_numbers = [x for x in range(10) if x % 2 == 0]
4. getattr
function: Dynamically get a property of an object.
class MyClass:
name = "Chat"
obj = MyClass()
print(getattr(obj, 'name')) # Outputs: Chat
5. setattr
function: Dynamically set a property of an object.
setattr(obj, 'name', 'Chat')
print(obj.name) # Outputs: Chat
6. Function argument unpacking: You can unpack lists or tuples into function arguments using *
.
def func(a, b, c):
print(a, b, c)
args = [1, 2, 3]
func(*args)
7. Dictionary unpacking in function arguments: Use **
to unpack dictionaries into keyword arguments.
def func(a=0, b=0):
print(a, b)
kwargs = {'a': 1, 'b': 2}
func(**kwargs)
8. zip
function: Combine multiple iterables into one.
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
9. eval
function: Evaluate a string as a Python expression.
result = eval("5 * 5")
print(result) # Outputs: 25
10. exec
function: Execute dynamically created Python code.
exec("print('Hello World')")
11. slice
objects: Create slice objects for slicing operations.
my_list = [0, 1, 2, 3, 4, 5]
s = slice(1, 5, 2)
print(my_list[s]) # Outputs: [1, 3]
12. globals
and locals
functions: Access global and local symbol tables.
x = 10
def func():
y = 5
print(globals()['x']) # Access global variable
print(locals()['y']) # Access local variable
func()
13. reversed
function: Reverse any sequence.
for i in reversed(range(5)):
print(i)
14. any
and all
functions: Check if any or all elements in an iterable are true.
print(any([False, True, False])) # Outputs: True
print(all([True, True, True])) # Outputs: True
15. defaultdict
from collections
: Provides a default value for a missing key.
from collections import defaultdict
d = defaultdict(int)
d[‘key’] += 1
print(d[‘key’]) # Outputs: 1
16. Counter
from collections
: Count items in an iterable.
from collections import Counter
c = Counter('hello')
print(c) # Outputs: Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})
17. itertools
module: Provides a collection of tools for handling iterators.
import itertools
for p in itertools.permutations('AB'):
print(p)
18. @staticmethod
and @classmethod
decorators: Define methods that are not bound to an instance or class.
class MyClass:
@staticmethod
def static_method():
return "static method called"
@classmethod
def class_method(cls):
return cls.__name__
print(MyClass.static_method())
print(MyClass.class_method())
19. __slots__
in classes: Optimize memory usage by explicitly declaring instance attributes.
class MyClass:
__slots__ = ['name', 'value']
def __init__(self, name, value):
self.name = name
self.value = value
20. frozenset
: Immutable version of a set.
my_set = frozenset([1, 2, 3])
print(my_set)
21. divmod
function: Returns the quotient and remainder when dividing two numbers.
quotient, remainder = divmod(10, 3)
print(f"Quotient: {quotient}, Remainder: {remainder}")
22. namedtuple
from collections
: Creates tuple-like objects with named fields.
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
print(p.x, p.y)
23. iter
function with sentinel value: Create an iterator that stops at a sentinel value.
with open('file.txt', 'r') as f:
for line in iter(lambda: f.readline().strip(), 'END'):
print(line)
24. List slicing tricks: Advanced ways to slice lists.
my_list = [0, 1, 2, 3, 4, 5]
print(my_list[::2]) # Outputs every second element
25. itertools.cycle
: Cycle through an iterable indefinitely.
import itertools
count = 0
for item in itertools.cycle(['A', 'B', 'C']):
if count > 5:
break
print(item)
count += 1
26. itertools.chain
: Chain multiple iterables.
import itertools
for i in itertools.chain([1, 2, 3], ['a', 'b']):
print(i)
27. itertools.combinations
and itertools.permutations
: Generate combinations and permutations.
import itertools
print(list(itertools.combinations('ABC', 2)))
print(list(itertools.permutations('ABC', 2)))
28. functools.partial
: Create partial functions with pre-filled arguments.
from functools import partial
def multiply(x, y):
return x * y
double = partial(multiply, 2)
print(double(5))
29. functools.lru_cache
: Cache function call results.
from functools import lru_cache
@lru_cache(maxsize=32)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
30. contextlib.suppress
: Suppress specified exceptions.
from contextlib import suppress
with suppress(FileNotFoundError):
open('non_existent_file.txt')
31. next
with default: Get the next item from an iterator, with a default if exhausted.
it = iter([1, 2, 3])
print(next(it, 'done')) # Outputs 1
print(next(it, 'done')) # Outputs 2
print(next(it, 'done')) # Outputs 3
print(next(it, 'done')) # Outputs 'done'
32. operator.itemgetter
: Efficiently fetch items from a collection.
from operator import itemgetter
data = [('Alice', 25), ('Bob', 30), ('Charlie', 35)]
print(sorted(data, key=itemgetter(1))) # Sort by age
33. operator.attrgetter
: Fetch attributes from objects.
from operator import attrgetter
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
people = [Person('Alice', 30), Person('Bob', 25)]
print(sorted(people, key=attrgetter('age')))
34. string.ascii_letters
and related constants: Predefined string constants.
import string
print(string.ascii_letters)
print(string.digits)
35. os.walk
: Traverse directory trees.
import os
for root, dirs, files in os.walk('.'):
print(root, dirs, files)
36. glob.glob
: Pattern matching for file names.
import glob
for filename in glob.glob('*.txt'):
print(filename)
37. heapq
module: Provides functions for implementing heaps.
import heapq
heap = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
heapq.heapify(heap)
heapq.heappush(heap, -5)
print([heapq.heappop(heap) for _ in range(3)])
38. bisect
module for binary search: Insert into a list in sorted order.
import bisect
a = [1, 2, 4, 5]
bisect.insort(a, 3)
print(a)
39. collections.deque
: Double-ended queue.
from collections import deque
d = deque('ghi')
d.append('j')
d.appendleft('f')
print(d)
40. csv
module for CSV file handling: Read and write CSV files.
import csv
with open('example.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['Name', 'Age'])
writer.writerow(['Alice', 30])
writer.writerow(['Bob', 25])
41. filter
function: Filters elements of an iterable based on a function.
numbers = [1, 2, 3, 4, 5]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers)) # Outputs: [2, 4]
42. map
function: Applies a function to every item of an iterable.
squares = map(lambda x: x**2, numbers)
print(list(squares)) # Outputs: [1, 4, 9, 16, 25]
43. complex
for complex numbers: Creates a complex number.
c = complex(2, 3)
print(c) # Outputs: (2+3j)
44. __dict__
in classes: Access the properties of an object.
class MyClass:
def __init__(self):
self.a = 1
self.b = 2
obj = MyClass()
print(obj.__dict__) # Outputs: {'a': 1, 'b': 2}
45. itertools.tee
: Creates n independent iterators from a single iterable.
import itertools
iter1, iter2 = itertools.tee(numbers, 2)
print(list(iter1), list(iter2))
46. itertools.islice
: Slicing for iterators.
slice_iter = itertools.islice(range(10), 2, 6)
print(list(slice_iter)) # Outputs: [2, 3, 4, 5]
47. itertools.starmap
: Similar to map
but arguments are obtained from the iterable.
data = [(2, 5), (3, 2), (10, 3)]
result = itertools.starmap(pow, data)
print(list(result)) # Outputs: [32, 9, 1000]
48. collections.ChainMap
: Groups multiple dictionaries into a single view.
from collections import ChainMap
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
combined = ChainMap(dict1, dict2)
print(combined['a']) # Outputs: 1
49. functools.reduce
: Applies a function cumulatively to the items of an iterable.
from functools import reduce
sum_of_numbers = reduce(lambda x, y: x + y, numbers)
print(sum_of_numbers) # Outputs: 15
50. itertools.accumulate
: Returns accumulated sums or other binary functions.
import itertools
acc = itertools.accumulate(numbers, lambda x, y: x + y)
print(list(acc)) # Outputs: [1, 3, 6, 10, 15]
51. functools.total_ordering
: Decorator to automatically generate ordering methods.
from functools import total_ordering
@total_ordering
class MyClass:
def __init__(self, value):
self.value = value
def __eq__(self, other):
return self.value == other.value
def __lt__(self, other):
return self.value < other.value
52. hashlib
for hashing: Generate hash values from strings.
import hashlib
hash_value = hashlib.sha256(b'Hello World').hexdigest()
print(hash_value)
53. sys.getsizeof
: Get the size of an object in bytes.
import sys
num = 5
print(sys.getsizeof(num)) # Outputs: Size in bytes
54. shlex.split
: Split the string using shell-like syntax.
import shlex
cmd = 'ls -l /var/www'
print(shlex.split(cmd))
55. os.environ
: Access environment variables.
import os
print(os.environ['PATH'])
56. calendar
module: Useful functions related to calendars.
import calendar
print(calendar.isleap(2024)) # Checks if a year is leap
57. uuid
module for unique IDs: Generate universally unique IDs.
import uuid
unique_id = uuid.uuid4()
print(unique_id)
58. asyncio
for asynchronous programming: Write concurrent code using async
/await
syntax.
import asyncio
async def main():
await asyncio.sleep(1)
print('Hello')
asyncio.run(main())
59. __name__ == "__main__"
: Checks if the script is run directly.
if __name__ == "__main__":
print("Script run directly")
60. pprint
for pretty printing: Print Python data structures in a formatted way.
import pprint
data = {'a': [1, 2, 3], 'b': [4, 5, 6]}
pprint.pprint(data)
Conclusion
The 60 Python hidden features and functions explored above unveil the depth and versatility of Python. From enhancing code efficiency with lesser-known data structures and itertools, ensuring robust and cleaner code with context managers and decorators, to harnessing the full potential of object-oriented features and memory management, these elements underscore Python’s capacity to cater to a wide array of programming needs.
Visit us at DataDrivenInvestor.com
Subscribe to DDIntel here.
Have a unique story to share? Submit to DDIntel here.
Join our creator ecosystem here.
DDIntel captures the more notable pieces from our main site and our popular DDI Medium publication. Check us out for more insightful work from our community.
DDI Official Telegram Channel: https://t.me/+tafUp6ecEys4YjQ1