Counter({‘apple‘: 3, ‘banana‘: 1, ‘orange‘: 1, ‘pear‘: 1})

Python is known for being a concise and readable programming language, but there are always ways to make your Python code even cleaner and more efficient. In this article, we‘ll go over five essential Python tips and tricks that will help you write better code in less time.

1. Use List Comprehensions for Concise List Creation

List comprehensions provide a compact way to create lists based on existing lists. They allow you to write an expression followed by a for clause, making them more concise than a for loop.

Here‘s an example of creating a new list using a for loop:


squares = [] for x in range(10):
squares.append(x**2)

Using a list comprehension, you can simplify this to:


squares = [x**2 for x in range(10)]

List comprehensions aren‘t limited to just lists – you can also use set and dictionary comprehensions for creating sets and dictionaries:


square_dict = {x: x2 for x in range(10)} # dictionary comprehension
square_set = {x
2 for x in range(10)} # set comprehension

When you find yourself using a for loop to create a list, set, or dictionary based on some other iterable, consider using a comprehension instead for more readable code.

2. Leverage Built-in Functions and Modules

Python comes with a wide variety of useful built-in functions and modules that can save you from having to write your own code for common tasks. Familiarizing yourself with what‘s available will make you a more efficient Python programmer.

For example, instead of writing a loop to find the smallest item in a list, you can use the built-in min() function:


numbers = [3, 5, 2, 8, 1] smallest = min(numbers) # returns 1

The any() and all() functions are handy for checking conditions. any() returns True if any element of an iterable is true, while all() returns True if all elements are true:


vals = [True, False, True] if any(vals):
print("At least one True value")

if all(vals):
print("All values are True")

Python‘s standard library also has many useful modules for common programming tasks. The collections module provides alternatives to Python‘s general purpose built-in containers like dict and list. For example, Counter lets you count hashable objects, defaultdict allows you to specify a default value for missing keys, and OrderedDict remembers the insertion order of keys.


from collections import Counter

fruit = ["apple", "banana", "apple", "orange", "pear", "apple"] fruit_counts = Counter(fruit)

The itertools module has a set of functions for working with iterators. For example, product() computes the Cartesian product of input iterables:


from itertools import product

p = product([1, 2], [3, 4])
print(list(p)) # [(1, 3), (1, 4), (2, 3), (2, 4)]

There are many other functions in itertools for combining, filtering, and manipulating iterables. Refer to the Python docs for the full list.

3. Use the Ternary Operator for Simple Conditionals

Python‘s ternary operator, also known as conditional expressions, allow you to write an if-else statement in one line of code. They follow this syntax:


value_if_true if condition else value_if_false

Here‘s an example of assigning a value to a variable based on a condition using an if-else statement:


num = 8
if num >= 0:
sign = "positive"
else:
sign = "negative"

Using a ternary operator, you can write this more concisely as:


num = 8
sign = "positive" if num >= 0 else "negative"

The ternary operator is best for simple conditionals. For more complex logic, a regular if-else statement is likely more readable.

4. Use F-strings for String Formatting

Python 3.6 introduced formatted string literals, also called f-strings, which provide a concise way to embed expressions inside string literals.

Prior to f-strings, the most common ways to format strings were with the % operator or the str.format() method:


name = "Alice"
age = 30
print("My name is %s and I‘m %d years old." % (name, age))
print("My name is {} and I‘m {} years old.".format(name, age))

With f-strings, you can embed variables and expressions directly in the string by prefixing it with ‘f‘ and wrapping expressions in curly braces {}:


name = "Alice"
age = 30
print(f"My name is {name} and I‘m {age} years old.")

F-strings also allow more advanced formatting options, like specifying alignment, width, and precision:


val = 12.3
print(f"The value is {val:.2f}") # displays "The value is 12.30"

F-strings are more readable than other string formatting methods since you can see the actual values right in the string rather than having to match up positional arguments.

5. Refactor Repeated Code into Helper Functions

If you find yourself writing similar code multiple times, it‘s a good practice to refactor that code into a reusable helper function. This makes your code more DRY (Don‘t Repeat Yourself), readable, and maintainable.

Let‘s say you have code that needs to make an HTTP request to a URL, check for errors, and return the response data:


import requests

resp = requests.get("https://api.example.com/endpoint1")
if resp.status_code != 200:
raise ApiError(f"GET /endpoint1 returned {resp.status_code}")
data = resp.json()

resp = requests.get("https://api.example.com/endpoint2")
if resp.status_code != 200:
raise ApiError(f"GET /endpoint2 returned {resp.status_code}")
data = resp.json()

You can refactor this repeated code into a get_data() helper function:


def get_data(endpoint):
resp = requests.get(f"https://api.example.com/{endpoint}")
if resp.status_code != 200:
raise ApiError(f"GET /{endpoint} returned {resp.status_code}")
return resp.json()

data1 = get_data("endpoint1")
data2 = get_data("endpoint2")

Now if the way you fetch data from the API changes, you only have to update the code in one place rather than everywhere you make a request.

Anytime you have code that‘s repeated multiple times, consider if it can be pulled out into a separate function. Smaller, single-purpose functions with descriptive names make your code more modular and easier to debug.

Wrapping Up

These five tips show just a few of the ways you can write more Pythonic code. Python has many features and idioms that allow you to write concise, readable programs.

Some other tips worth looking into:

  • Use multiple assignment to assign several variables at once: x, y, z = 1, 2, 3
  • Take advantage of Python‘s comparison chaining: if 18 <= age < 65
  • Use generator expressions: (x**2 for x in range(10)) returns an iterator of squares
  • The zip() function pairs up elements from iterables: list(zip([‘a‘, ‘b‘], [1, 2])) returns [(‘a‘, 1), (‘b‘, 2)]
  • Unpack function arguments using *args and **kwargs

The Python docs, as well as books like "Effective Python" and "Fluent Python", are great resources for diving deeper into Python‘s capabilities and best practices. The more familiar you become with Python‘s features, the more efficiently you‘ll be able to write clean, idiomatic Python code.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Similar Posts