50+ Python 3 Tips & Tricks
Last Updated on July 25, 2023 by Editorial Team
Author(s): Eyal Trabelsi
Originally published on Towards AI.
Programming, Python
These Python Gems Will Make Your Code Beautiful and Elegant
Here is a list of python tips and tricks to help you write an elegant Python 3 code! This article is divided into different kinds of tricks:
- Python iterable tricks.
- Python comprehension tricks.
- Python unpacking tricks.
- Python itertools tricks.
- Python collections tricks.
- Python other tricks.
- Python easter eggs.
- Python tricks to understand the context.
Python Iterables tricks
Creating a sequence of numbers (zero to ten with skips).
Summing a sequence of numbers (calculating the sum of zero to ten with skips).
Checking whether any element in the sequence is Truthful (checking whether any elements between zero and ten with skips are even).
Checking whether all elements in the sequence are Truthful (checking whether all elements between zero and ten with skips are even).
Cumulative summing a sequence of numbers (calculating the cumulative sum of zero to ten with skips).
Given each iterable we construct a tuple by adding an index.
Concatenating iterable to a single string.
Combining two iterable of tuples or pivot nested iterables.
Getting min/max from iterable (with/without specific function).
Getting sorted iterable (can sort by βcompareβ function).
Splitting a single string to list.
Initializing a list filled with some repetitive number.
Merging/Upserting two dictionaries.
Naming and saving slices of iterables.
Finding the index of an item in a list.
Finding the index of the min/max item in an iterable.
Rotating iterable by k elements.
Removing useless characters on the end/start/both of your string.
Reversing an iterable wit order (string, list etc).
Python branching tricks
Multiple predicates short-cut.
For-else construct useful when searched for something and find it.
Trenary operator.
Try-catch-else construct.
While-else construct.
Python comprehensions tricks
List comprehension.
Set comprehension.
Dict comprehension.
Generator comprehension.
List comprehension with the current and previous value.
Note: all comprehension can use predicates with if statement.
Python unpacking tricks
Unpack variables from iterable.
Swap variables values.
Unpack variables from iterable without indicating all elements.
Unpack variables using the splat operator.
Python Itertools tricks
Flatten iterables.
Creating cartesian products from iterables.
Creating permutation from iterable.
Creating ngram from iterable.
Combining two iterables of tuples with padding or pivot nested iterable with padding.
Creating a combination of k things from an iterable of n
Creating accumulated results of iterable given a function
Creating an iterator that returns elements from the iterable as long as the predicate is true
Creating an iterator that filters elements from iterable returning only those for which the predicate is False
Creating an iterator that computes the function using arguments obtained from the iterable of iterables
Python collections tricks
Set basic operations.
Counter data structure (an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values).
Default dictionary structure (a subclass of dictionary that retrieves default value when non-existing key getting accessed).
Ordered dict structure (a subclass of dictionary that keeps order).
Deques structure (Deques are a generalization of stacks and queues).
Named tuples structure (create tuple-like objects that have fields accessible by attribute lookup as well as being indexable and iterable).
Use A Dictionary To Store A Switch.
Data classes structure
Other Python tricks
Generating uuid.
Memoization using LRU cache.
Suppression of expressions
Creating context managers when setup and teardown is needed
28.7. contextlib – Utilities for with-statement contexts – Python 2.7.16 documentation
Edit description
docs.python.org
An elegant way to deal with a file path (3.4β₯)
Implementing standard operators as functions for our classes
operator – Standard operators as functions – Python 3.7.4 documentation
The module exports a set of efficient functions corresponding to the intrinsic operators of Python. For example, isβ¦
docs.python.org
Creating decorator to separate concerns
Using yield to create a simple iterator
yield from use cases and tricks
In practice, what are the main uses for the new "yield from" syntax in Python 3.3?
Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question. Provide details and shareβ¦
stackoverflow.com
Python easter eggs
Anti-gravity
The Zen of Python
Another cool Easter-eggs can be found
OrkoHunter/python-easter-eggs
Curated list of all the easter eggs and hidden jokes in Python – OrkoHunter/python-easter-eggs
github.com
Python tricks to understand the context
Explicitly mark entry point using __main__.py file
Use __main__.py
We have all seen the __init__.py file and know its role, but what is ? I have seen many Python projects either onβ¦
shaneoneill.io
List object attributes
Make regex readable
Additional information on a live object
inspect – Inspect live objects – Python 3.7.4 documentation
The module provides several useful functions to help get information about live objects such as modules, classesβ¦
docs.python.org
Summary
If you think I should add any more or have suggestions please do let me know in the comments. Iβll keep on updating this blog.
Join thousands of data leaders on the AI newsletter. Join over 80,000 subscribers and keep up to date with the latest developments in AI. From research to projects and ideas. If you are building an AI startup, an AI-related product, or a service, we invite you to consider becoming aΒ sponsor.
Published via Towards AI