20 Everyday Tips & Tricks in Python
Table of Contents
Introduction
This tutorial covers 20 practical tips and tricks for using Python effectively. Whether you're a beginner or looking to refine your skills, these insights will help you write cleaner, more efficient code. Each tip is straightforward and includes examples to demonstrate how you can apply them in your own projects.
Chapter 1: Variable swapping
Swapping variables in Python is simple and can be done in one line.
- Assign two variables, for example:
a = "text" b = 100
- Swap the values:
a, b = b, a
- You can also swap three variables:
c = "more text" a, b, c = c, a, b
Chapter 2: Reversing iterables
You can easily reverse lists or strings in Python using slicing or the reversed()
function.
- To reverse a list:
my_list = [1, 2, 3, 4] reversed_list = my_list[::-1]
- To reverse a string:
my_string = "hello" reversed_string = my_string[::-1]
Chapter 3: Multiplying strings
You can create repeated strings using multiplication.
- Define a string:
shout = "A"
- Multiply it by a number:
shout_result = shout * 20 # "AAAAAAAAAAAAAAAAAAAA"
Chapter 4: One line conditions
You can write concise conditional statements in a single line.
number = 10
result = "even" if number % 2 == 0 else "odd"
print(result) # Output: even
Chapter 5: Joining strings
To concatenate a list of strings into a single formatted string, use the join()
method.
- Create a list of emails:
emails = ["example1@gmail.com", "example2@gmail.com", "example3@gmail.com"]
- Join them with a comma:
formatted_emails = ", ".join(emails) print(formatted_emails) # Output: example1@gmail.com, example2@gmail.com, example3@gmail.com
Chapter 6: Getting values from dictionaries
To safely access values from a dictionary, use the get()
method to avoid key errors.
my_dict = {"name": "Alice", "age": 25}
age = my_dict.get("age") # returns 25
unknown_value = my_dict.get("unknown_key", "default_value") # returns "default_value"
Chapter 7: Setting default values in dictionaries
You can use setdefault()
to return a value if a key doesn’t exist, and set it if necessary.
scores = {"Bob": 90}
james_score = scores.setdefault("James", 0) # returns 0 and adds James to the dictionary
Chapter 8: Using counters
The Counter
class from the collections
module helps track the frequency of elements in an iterable.
from collections import Counter
letters = ['a', 'b', 'a', 'c', 'b', 'a']
counter = Counter(letters)
print(counter.most_common(2)) # Output: [('a', 3), ('b', 2)]
Chapter 9: Specifying a start in enumerate
When using enumerate()
, you can specify the starting index.
for index, letter in enumerate(['a', 'b', 'c'], start=1):
print(index, letter) # Outputs: 1 a, 2 b, 3 c
Chapter 10: Dictionary merging
You can merge dictionaries easily using the |
operator in Python 3.9+.
dict_a = {'A': 1, 'B': 2}
dict_b = {'C': 3, 'D': 4}
merged_dict = dict_a | dict_b # {'A': 1, 'B': 2, 'C': 3, 'D': 4}
Chapter 11: Underscore formatting
Use underscores in numeric literals for better readability.
big_number = 1_000_000 # 1 million
print(big_number) # Output: 1000000
Chapter 12: Callable classes
You can make a class instance callable by implementing the __call__
method.
class Multiplier:
def __init__(self, value):
self.value = value
def __call__(self, other_value):
return self.value * other_value
double = Multiplier(2)
print(double(10)) # Output: 20
Chapter 13: Method chaining
Return self
in methods to allow chaining.
class Person:
def __init__(self, name):
self.name = name
def modify_name(self, new_name):
self.name = new_name
return self
bob = Person("Bob")
bob.modify_name("James").modify_name("Alice")
print(bob.name) # Output: Alice
Chapter 14: Formatted list printing
Unpack and format elements from a list when printing.
foods = ["apples", "bananas", "cherries"]
print(*foods, sep=", ", end=".") # Output: apples, bananas, cherries.
Chapter 15: Representation in classes
Implement __repr__
for a more useful string representation of class instances.
class Person:
def __init__(self, name):
self.name = name
def __repr__(self):
return f"Person(name={self.name})"
bob = Person("Bob")
print(bob) # Output: Person(name=Bob)
Chapter 16: Unpacking elements
Use unpacking to get the first and last elements from an iterable.
people = ["Bob", "James", "George", "Sophia"]
first, *_, last = people
print(first, last) # Output: Bob Sophia
Chapter 17: Quick debugging
Use f-strings to quickly debug variable names and their values.
name = "Alice"
age = 25
print(f"name={name}, age={age}") # Output: name=Alice, age=25
Chapter 18: Rounding numbers
Use the round()
function to round numbers to a specified number of decimal places.
number = 12.34567
rounded_number = round(number, 2) # Output: 12.35
Chapter 19: String replacement
Replace substrings using the replace()
method.
sentence = "The tired Red Fox on the red Farm ate a bored red pig."
new_sentence = sentence.replace("red", "blue")
print(new_sentence) # Output: The tired Blue Fox on the blue Farm ate a bored blue pig.
Chapter 20: Max and min with custom keys
You can define a custom key function for max()
and min()
.
names = ["Timothy", "Bob", "James", "Zebra"]
max_name = max(names, key=lambda x: x.lower().count('a'))
print(max_name) # Output: Amanda (or whichever name has most 'a's)
Conclusion
These 20 tips and tricks can enhance your Python programming skills and improve code readability and efficiency. Experiment with these techniques in your projects to become more proficient in Python. Happy coding!