Fundamentals 15 min read

15 Concise Python Tips for Efficient Coding

This article presents fifteen practical Python techniques—including multi‑key sorting, data classes, list comprehensions, memory inspection, frequency analysis, attrs usage, dictionary merging, multiple return values, filtering, mapping, zipping, reversing, existence checks, flattening nested lists, and uniqueness testing—each illustrated with clear code examples and explanations.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
15 Concise Python Tips for Efficient Coding

1. Sorting Objects by Multiple Keys

Shows how to sort a list of dictionaries by both name and age using Python's stable sort and operator.itemgetter , mirroring the SQL query SELECT * FROM people ORDER BY name, age .

<code>people = [
    {'name': 'John', 'age': 64},
    {'name': 'Janet', 'age': 34},
    {'name': 'Ed', 'age': 24},
    {'name': 'Sara', 'age': 64},
    {'name': 'John', 'age': 32},
    {'name': 'Jane', 'age': 34},
    {'name': 'John', 'age': 99}
]
</code>
<code>import operator
people.sort(key=operator.itemgetter('age'))
people.sort(key=operator.itemgetter('name'))
</code>

The resulting order places entries with the same name together, sorted further by age.

2. Data Classes

Introduces Python 3.7+ dataclass feature, highlighting reduced boilerplate, automatic __eq__ , type hints, and readable __repr__ .

<code>from dataclasses import dataclass

@dataclass
class Card:
    rank: str
    suit: str

card = Card('Q', 'hearts')
print(card == card)   # True
print(card)           # Card(rank='Q', suit='hearts')
</code>

3. List Comprehensions

Demonstrates the compact syntax [expression for item in list if condition] for generating lists.

<code>mylist = [i for i in range(10)]
print(mylist)  # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</code>

Shows mathematical operations and function calls within comprehensions.

<code>squares = [i**2 for i in range(10)]
print(squares)  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

def some_function(a):
    return (a + 5) / 2
my_formula = [some_function(i) for i in range(10)]
print(my_formula)  # [2.5, 3.0, ..., 7.0]
</code>

4. Checking Object Memory Usage

Uses sys.getsizeof() to compare memory footprints of a range object versus an actual list.

<code>import sys
mylist = range(0, 10000)
print(sys.getsizeof(mylist))  # 48 bytes
myreallist = [x for x in range(0, 10000)]
print(sys.getsizeof(myreallist))  # 87632 bytes
</code>

5. Finding the Most Frequent Value

Shows a one‑liner using max(set(seq), key=seq.count) and a more efficient collections.Counter approach.

<code>test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
print(max(set(test), key=test.count))  # 4

from collections import Counter
print(Counter(test).most_common(1))   # [(4, 4)]
</code>

6. attrs Package

Explains using the third‑party attrs library for richer data‑class‑like features and shows a basic example.

<code>@attrs
class Person(object):
    name = attrib(default='John')
    surname = attrib(default='Doe')
    age = attrib(init=False)

p = Person()
print(p)               # Person(name='John', surname='Doe', age=NOTHING)
 p = Person('Bill', 'Gates')
 p.age = 60
print(p)               # Person(name='Bill', surname='Gates', age=60)
</code>

7. Merging Dictionaries (Python 3.5+)

Shows merging with unpacking {**dict1, **dict2} and the newer pipe operator introduced in Python 3.9.

<code>dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged = {**dict1, **dict2}
print(merged)  # {'a': 1, 'b': 3, 'c': 4}

# Python 3.9+
merged = dict1 | dict2
</code>

8. Returning Multiple Values

Illustrates that a function can return a tuple of values, e.g., return name, birthdate , and notes that more than three values should be wrapped in a class or dataclass.

<code>def get_user(id):
    # fetch user from database
    return name, birthdate

name, birthdate = get_user(4)
</code>

9. Filtering List Elements

Demonstrates filter() with a predicate function and the equivalent list‑comprehension.

<code>original_list = [1, 2, 3, 4, 5]

def filter_three(number):
    return number > 3

filtered = list(filter(filter_three, original_list))
print(filtered)  # [4, 5]

# List comprehension version
filtered = [n for n in original_list if n > 3]
print(filtered)  # [4, 5]
</code>

10. Mapping List Elements

Shows map() to apply a function to each element and the list‑comprehension alternative.

<code>original_list = [1, 2, 3, 4, 5]

def square(number):
    return number ** 2

squares = list(map(square, original_list))
print(squares)  # [1, 4, 9, 16, 25]

# List comprehension version
squares = [n**2 for n in original_list]
print(squares)
</code>

11. Combining Lists with zip()

Uses zip() to pair elements from two lists and iterate over the pairs.

<code>numbers = [1, 2, 3]
letters = ['a', 'b', 'c']
combined = list(zip(numbers, letters))
print(combined)  # [(1, 'a'), (2, 'b'), (3, 'c')]
for num, let in zip(numbers, letters):
    print(num, '\t', let)
</code>

12. Reversing a List

Shows the slice syntax list[::-1] to obtain a reversed list.

<code>original_list = [1, 2, 3, 4, 5]
reversed_list = original_list[::-1]
print('Reversed:', reversed_list)  # [5, 4, 3, 2, 1]
</code>

13. Checking Element Existence

Uses the in operator inside a helper function to report whether an item is present in a list.

<code>games = ['Yankees', 'Yankees', 'Cubs', 'Blue Jays', 'Giants']

def isin(item, lst):
    if item in lst:
        print(f"{item} is in the list!")
    else:
        print(f"{item} is not in the list!")

isin('Blue Jays', games)
isin('Angels', games)
</code>

14. Flattening Nested Lists

Shows a double‑loop list comprehension to flatten a two‑level nested list, and mentions the third‑party tree library for arbitrary depth.

<code>nested_list = [[1,2,3],[4,5,6],[7,8,9]]
flat_list = [i for sub in nested_list for i in sub]
print(flat_list)  # [1,2,3,4,5,6,7,8,9]

# Using dm‑tree
import tree
print(tree.flatten(nested_list))
</code>

15. Checking Uniqueness

Compares the length of a list with the length of its set to determine if all elements are unique.

<code>def is_unique(seq):
    if len(seq) == len(set(seq)):
        print('Unique!')
    else:
        print('Not unique!')

is_unique([1,2,3,4,5])   # Unique!
is_unique([1,1,2,3,4])   # Not unique!
</code>
Programmingfunctionsdictionarylist comprehensiontipsdataclasses
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.