10 Practical Python Code Tricks for Efficient Programming
This article presents ten useful Python techniques—including string joining, list comprehensions, enumerate, zip, itertools, Counter, dictionary creation, generators, multiple return values, and the sorted function—each explained with clear examples and performance comparisons to help developers write cleaner and faster code.
Python is highlighted as one of the fastest‑growing and most popular programming languages, with many companies such as Netflix, IBM, and Dropbox relying on it for production code.
Key advantages of Python include cross‑platform compatibility, a rich ecosystem of open‑source libraries, readable and maintainable syntax, a powerful standard library, and built‑in support for test‑driven development.
1. String concatenation with join() Instead of repeatedly adding strings in a loop, use ''.join(characters) for efficient concatenation. characters = ['p', 'y', 't', 'h', 'o', 'n'] word = "".join(characters) print(word)
2. List comprehensions Create new lists from iterables in a single, optimized expression. Example: generate squares of the first five integers. m = [x ** 2 for x in range(5)] print(m) # [0, 1, 4, 9, 16]
3. Using enumerate() for indexed loops (FizzBuzz) Iterate with both index and value, applying conditional logic for classic interview problems. numbers = [30, 42, 28, 50, 15] for i, num in enumerate(numbers): if num % 3 == 0 and num % 5 == 0: numbers[i] = 'fizzbuzz' elif num % 3 == 0: numbers[i] = 'fizz' elif num % 5 == 0: numbers[i] = 'buzz' print(numbers) # ['fizzbuzz', 'fizz', 28, 'buzz', 'fizzbuzz']
4. Merging lists with zip() Combine parallel sequences, such as countries and capitals, into paired output. countries = ['France', 'Germany', 'Canada'] capitals = ['Paris', 'Berlin', 'Ottawa'] for country, capital in zip(countries, capitals): print(country, capital)
5. itertools utilities Generate combinatorial data efficiently; for example, all 2‑element combinations of a team list. import itertools friends = ['Team 1', 'Team 2', 'Team 3', 'Team 4'] print(list(itertools.combinations(friends, r=2)))
6. Sets and Counter() Count occurrences of items in an iterable using collections.Counter . from collections import Counter count = Counter(['a', 'b', 'c', 'd', 'b', 'c', 'd', 'b']) print(count) # Counter({'b': 3, 'c': 2, 'd': 2, 'a': 1})
7. Converting two lists to a dictionary Use dict(zip(keys, values)) to map student names to scores. students = ['Peter', 'Julia', 'Alex'] marks = [84, 65, 77] dictionary = dict(zip(students, marks)) print(dictionary) # {'Peter': 84, 'Julia': 65, 'Alex': 77}
8. Generators for large data Replace list comprehensions with generator expressions to reduce memory usage and improve speed when summing massive ranges. t1 = time.clock() sum((i * i for i in range(1, 100000000))) t2 = time.clock() print(f"It took {t2 - t1} Secs to execute this method")
9. Returning multiple values from a function Python functions can return tuples, allowing simultaneous retrieval of related results. def multiplication_division(num1, num2): return num1 * num2, num1 / num2 product, division = multiplication_division(15, 3) print("Product=", product, "Quotient=", division)
10. Sorting with sorted() The built‑in sorted() returns a new sorted list for any iterable; it supports both ascending and descending order. sorted([3,5,2,1,4]) # [1, 2, 3, 4, 5] sorted(['france', 'germany', 'canada'], reverse=True) # ['germany', 'france', 'canada']
These ten snippets demonstrate how Python’s expressive syntax and standard library can simplify everyday programming tasks while delivering measurable performance gains.
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.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.