Programming, Python

50+ Python 3 Tips & Tricks

These Python Gems Will Make Your Code Beautiful and Elegant

Eyal Trabelsi
Jul 18, 2019 · 4 min read

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).

https://docs.python.org/3/library/collections.html#collections.Counter

Default dictionary structure (a subclass of dictionary that retrieves default value when non-existing key getting accessed).

https://docs.python.org/3/library/collections.html#collections.defaultdict

Ordered dict structure (a subclass of dictionary that keeps order).

https://docs.python.org/3/library/collections.html#collections.OrderedDict

Deques structure (Deques are a generalization of stacks and queues).

https://docs.python.org/3/library/collections.html#collections.deque

Named tuples structure (create tuple-like objects that have fields accessible by attribute lookup as well as being indexable and iterable).

https://docs.python.org/3/library/collections.html#collections.namedtuple

Use A Dictionary To Store A Switch.

Data classes structure

https://docs.python.org/3/library/dataclasses.html

Other Python tricks

Generating uuid.

Memoization using LRU cache.

Suppression of expressions

https://docs.python.org/3/library/contextlib.html

Creating context managers when setup and teardown is needed

An elegant way to deal with a file path (3.4≥)

https://medium.com/@ageitgey/python-3-quick-tip-the-easy-way-to-deal-with-file-paths-on-windows-mac-and-linux-11a072b58d5f

Implementing standard operators as functions for our classes

Creating decorator to separate concerns

For great long explanation visit https://gist.github.com/Zearin/2f40b7b9cfc51132851a

Using yield to create a simple iterator

yield from use cases and tricks

Python easter eggs

Anti-gravity

http://python-history.blogspot.com/2010/06/import-antigravity.html

The Zen of Python

Another cool Easter-eggs can be found

Python tricks to understand the context

Explicitly mark entry point using __main__.py file

List object attributes

Additional information on a live object

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.

Towards AI — Multidisciplinary Science Journal

The Best of Tech, Science and Engineering.

Sign up for Towards AI Newsletter

By Towards AI — Multidisciplinary Science Journal

Towards AI publishes the best of tech, science, and engineering. Subscribe with us to receive our newsletter right on your inbox. Take a look

Create a free Medium account to get Towards AI Newsletter in your inbox.

Eyal Trabelsi

Written by

Eyal is a data engineer at Salesforce with a passion for performance. His main areas of expertise are within data-intensive applications, improvement of process

Towards AI — Multidisciplinary Science Journal

Towards AI is a world’s leading multidisciplinary science journal. Towards AI publishes the best of tech, science, and engineering. Read by thought-leaders and decision-makers around the world.

Eyal Trabelsi

Written by

Eyal is a data engineer at Salesforce with a passion for performance. His main areas of expertise are within data-intensive applications, improvement of process

Towards AI — Multidisciplinary Science Journal

Towards AI is a world’s leading multidisciplinary science journal. Towards AI publishes the best of tech, science, and engineering. Read by thought-leaders and decision-makers around the world.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store