26 Python Tricks To Show Off to Your Colleagues

Tricks that will make your life easier as a Python developer

Anmol Tomar
CodeX

--

Pic Credit: Unsplash

Python is an incredibly versatile programming language that is extensively utilized and supported by a wide range of libraries and frameworks. However, within the vast Python ecosystem, there exist some lesser-known coding tricks and libraries that can significantly enhance your development experience and optimize your code.

In this blog, we will explore some of these less-known Python tricks that can be incredibly useful but are not widely known.

Let’s dive in and explore these cool tricks:

1. all or any

If you are you tired of writing complex conditional statements in your Python code? Look no further than all and any! These built-in functions can help simplify your logic by testing if all or any elements in an iterable evaluate to True. It's like having a personal assistant who can filter out the bad apples for you.

list1 = [True, True, False, True] 
print(all(list1))
# False

list2 = [False, True, False]
print(any(list2))
# True

The all function returns True if all elements in the iterable are true, and False otherwise. The any function returns True if at least one element in the iterable is true, and False otherwise.

2. emoji

The emoji library provides a way to add colorful and expressive characters to your strings. Now, your code can convey your feelings without you having to say a word.

from emoji import emojize 
print(emojize(":thumbs_up: Python is awesome! :thumbs_up:"))

3. from __future__ import

The from __future__ import statement is used to enable new language features that are not compatible with older versions of Python. This clever hack allows you to enable newer Python features in older versions of the language. It's like a time machine for your code!

from __future__ import division 
print(5 / 2)
# 2.5

##Python 2.x would have returned integer 2.

4. inspect

Ever wonder what’s going on behind the scenes of your Python code? The inspect module can give you a peek under the hood! This handy tool lets you examine the attributes and source code of your objects at runtime. It's like being a detective in your own codebase.

import inspect 

## add function present in python_functions.py file
def add(x, y):
return x + y
## you want to inspect it in analysis.py file
print(inspect.getsource(add)))

5. newspaper3k

The newspaper3k library provides an easy way to scrape and extract content from news articles. It's like having a personal news assistant who can gather all the relevant information for you.

#!pip install newspaper3k

from newspaper import Article
url = "http://cnn.com/2023/03/29/entertainment/the-mandalorian-episode-5-recap/index.html"
article = Article(url)
article.download()
article.parse()
article.text
Image by Author

It provides the flexibility to scrape all the articles of a news website too.

6. Type hints

Type hints are used to annotate the types of variables and function arguments in your code. They are not enforced by Python but can be used to catch type errors and improve code quality.

def add(x: int, y: int) -> int: 
return x + y

7. wikipedia

The wikipedia library can save you the trouble of opening up Wikipedia in your browser to look up information! This library provides an easy-to-use interface to search and retrieve information from Wikipedia pages.

import wikipedia 
# Search for a page
results = wikipedia.search('Python (programming language)')
# Get the summary of the first result
summary = wikipedia.summary(results[0])
print(summary)
Image by Author

8. zip

The zip function is used to combine two or more iterables into a single iterable of tuples. It returns an iterator that aggregates elements from each of the iterables. The resulting iterator stops when the shortest input iterable is exhausted.

list1 = [1, 2, 3] 
list2 = ['a', 'b', 'c']
zipped = zip(list1, list2)


for i, j in zipped:
print(i, j)
#1 a
#2 b
#3 c

9. uuid

The uuid module provides the ability to generate UUIDs (Universally Unique Identifiers). UUIDs are 128-bit unique identifiers that are commonly used in computer systems and applications to identify objects, resources, and entities in a unique way. The uuid module can generate UUIDs using various algorithms, including the default version 4, which uses random numbers. Here's an example of how to generate a UUID using the uuid module:

import uuid

# Generate a random UUID
id = uuid.uuid4()
# Print the UUID
print(id)
#6c81a22b-5839-48ec-9f2f-842d7b96c425

10. pprint

The pprint module provides a way to pretty-print Python data structures, such as dictionaries and lists. Unlike the built-in print function, which prints the output in a single line or multiple lines without any formatting, the pprint function prints the output in a more readable and structured format, with indentation and line breaks.

It’s like having a professional organizer come in and declutter your code’s output!

Here’s an example of how to use the pprint module:

import pprint

data = {
'name': 'John',
'age': 30,
'address': {
'street': 'Main St',
'city': 'New York',
'state': 'NY'
}
}
pprint.pprint(data)
pprint (Image by Author)

You should use pprint instead of print when you want to print complex data structures in a human-readable format, especially when dealing with nested dictionaries or lists. The pprint output is more structured and easier to read, making it a useful tool for debugging or exploring your data. You can also customize the output formatting by adjusting the indentation level or other parameters.

This was part 2 of the Python tricks series, you can refer to part 1 here, where I have covered the remaining 16 Python tricks.

Conclusion

By using these lesser-known Python tricks and libraries, you can improve your coding efficiency and productivity. Whether you’re working on data analysis, web development, or any other programming project, these tools can help you save time and make your code more elegant and efficient. So, give them a try and see how they can improve your coding experience!

Thank You!

If you find my blogs useful, then you can follow me to get direct notifications whenever I publish a story.

--

--

Anmol Tomar
CodeX
Writer for

Top AI writer | Data Science Manager | Mentor. Want to kick off your career in Data Science? Get in touch with me: https://www.analyticsshiksha.com/