Python

10 Python Tricks That Will Level Up Your Code

Python rewards curiosity. The language's clean syntax hides features that even experienced developers overlook. Today, we'll explore practical techniques that eliminate boilerplate code, speed up debugging, and make your scripts more readable. These aren't academic curiosities—they solve real problems you encounter daily.

What happened

  • Configure pandas number formatting for cleaner DataFrames
  • Extract random items from lists without index calculations
  • Print iterable contents with minimal syntax
  • Inspect object attributes without documentation
  • Pause execution for interactive debugging
  • Analyze disk space used by installed packages

Controlling How Pandas Shows Numbers

DataFrames often display floating-point numbers with excessive precision. Use display options to round values:

“`python

Pd.set_option('precision', 2)

“`

For comma-separated thousands and controlled decimals:

“`python

Pd.options.display.float_format = '{:,.2f}'.format

“`

These settings apply to the entire session, making outputs consistent and easier to scan.

Picking Random Items from Sequences

The random module handles selection elegantly. Pass any indexable sequence:

“`python

Import random as r

Colors = ["red", "blue", "green", "yellow"]

Print(r.choice(colors))

“`

This works with lists, tuples, and strings. Here's a function that selects a random item and removes it from the source:

“`python

From random import choice

Def select_book(shelf):

Chosen = choice(shelf)

Shelf.remove(chosen)

Return chosen

“`

One caveat: empty sequences raise an IndexError, and dictionaries aren't directly supported since they're unordered.

Printing Iterables Without Loops

The common pattern for spaced output looks like this:

“`python

Numbers = [1, 2, 3, 5, 7]

For n in numbers:

Print(n, end=" ")

“`

The unpacking operator simplifies this:

“`python

Numbers = [1, 2, 3, 5, 7]

Print(*numbers)

“`

The asterisk distributes elements as separate arguments, inserting spaces automatically. This works with any iterable—lists, tuples, strings, or generators.

Discovering Object Capabilities

When you know an object exists but can't remember its methods, dir() lists everything:

“`python

Text = "Hello World"

Print(dir(text))

“`

The output includes dunder methods, string manipulation functions, and comparison operators. Searching this output reveals functions like upper(), lower(), split(), and replace() without leaving your editor.

Stopping Execution for Inspection

Python 3.7 introduced breakpoint(), a built-in debugging command:

“`python

For i in range(1, 20):

Breakpoint() # execution pauses here

If some_condition(i):

Process(i)

“`

This launches the pdb debugger at that line. You can inspect variables, step through code, and evaluate expressions interactively. No imports required.

Measuring Package Footprint

Your environment accumulates packages over time. To check installation paths:

“`bash

Pip3 show "package_name" | grep "Location:"

“`

Once you have the path, analyze disk usage:

“`bash

Du -h path/to/site-packages

“`

This reveals which packages consume the most space, helping you decide what to keep.

Our Analysis

These techniques share a pattern: they replace common workarounds with language features designed for the task. Unpacking eliminates loop-based printing. Breakpoint() eliminates import statements. Display options eliminate manual formatting logic.

For Android users who occasionally work with Python scripts—perhaps for automation or data processing—these shortcuts reduce cognitive load. Cleaner code means fewer bugs and faster iteration.

The most immediately useful tricks are random.choice() for testing scenarios and breakpoint() for tracking down unexpected behavior. Both require zero setup and work across environments.

What to Watch Next

Explore f-strings for string formatting, list comprehensions for concise transformations, and the walrus operator (:=) for inline assignments. These build on the patterns shown here and further reduce unnecessary syntax.

Key takeaways

  • Pandas display options make numerical data easier to read at a glance
  • Random selection works on any ordered sequence without index math
  • The unpacking operator replaces verbose printing loops entirely
  • Breakpoint() launches debugging without imports or configuration
  • Package size analysis helps manage disk space in development environments

Frequently asked questions

Does random.choice() work on dictionaries?

No, dictionaries aren't ordered by position. Use random.choice(list(my_dict.keys())) to get a random key.

What's the difference between breakpoint() and pdb.set_trace()?

Breakpoint() was introduced in Python 3.7 and requires no imports. It also respects the PYTHONBREAKPOINT environment variable for flexibility.

How do I format only specific columns in a DataFrame?

Use the .round() method on individual Series or apply custom formatting with .astype() and string methods.

Can I unpack multiple iterables simultaneously?

Yes. Use print(*list1, *list2) to interleave elements, or zip() to pair them: print(*zip(list1, list2)).

What happens if I call breakpoint() in production code?

Execution stops and waits for input. This is rarely desirable in deployed applications—use logging instead for production debugging.

Related