Python is loved for its simplicity and power, but did we know it has a bunch of cool features that can make our coding even more efficient and fun. In this guide, we’ll explore some Python tricks that can help us write cleaner, faster, and more Pythonic code.
Whether we’re looking to optimize our current code or just want to learn something new, these tips will give us a fresh perspective on Python’s capabilities.
1. Slicing
Python slicing is about obtaining a sub-string from the given string by slicing it respectively from start to end. The format in which slices are implemented is sequence[start:stop:step]. If no values are specified in the start, stop, and step parameters, then the sequence will implement the defaults.
Python String Slicing
In this example, we will see how we can reverse a string using the Python String Slicing technique.
Python
# initialize string
a = "Hello World!"
# display string
print(a[::-1])
Python List Slicing
In this example, we will see how we can reverse a list using the Python List Slicing technique.
Python
# Initialize list
Lst = [60, 70, 30, 20, 90, 10, 50]
# Display list
print(Lst[::1])
Output[60, 70, 30, 20, 90, 10, 50]
2. Generators
Generators are a special type of function in Python that allow us to create an iterator in a more memory-efficient way. Instead of returning a single value, generators "yield" values one at a time using the yield keyword.
Example:
In this example, the function simple_generator returns a generator object that yields the values 1, 2, and 3 one at a time.
Python
# generator function
def simple_generator():
yield 1
yield 2
yield 3
gen = simple_generator()
# print values
for value in gen:
print(value)
3. The ‘not’ Operator
The not operator in Python is a logical operator that is used to negate a boolean expression. It is one of the simplest and most intuitive operators in Python’s logic and helps evaluate conditions or expressions by inverting the truth value. In simpler terms, it converts a True expression to False, and a False expression to True.
Example:
In this example we will check if the list is empty using the not operator.
Python
4. Append Function
The append() method in Python is used to add an item to the end of a list. It modifies the original list by appending the given element.
Example:
In this example, we will add an element to the existing list.
Python
# initialize list
a = [1, 2, 3]
# append a value
a.append(4)
print(a)
Example:
In this example, we will append to a List in a Tuple. If we think of a tuple object as a sequence of names with bindings to objects that cannot be changed, we may see things differently. The first two elements of our tuple are integers - they are immutable. The last element of our tuple is a list, a mutable object in Python.
Python
# initialize a tuple
a = (1, 2, [1, 2, 3])
# append to the list in the tuple
a[2].append(4)
print(a)
Output(1, 2, [1, 2, 3, 4])
5. Merging Dictionaries
In Python, it is possible to merge dictionaries using update() method. There is not much else to say about this particular Python trick.
Example:
In this example, we have two dictionaries and we will merge them using the update() method.
Python
# initialize two dictionaries
a = {"a": 1, "b": 2}
b = {"c": 3, "d": 4}
# merge dictionaries
a.update(b)
print(a)
Output{'a': 1, 'b': 2, 'c': 3, 'd': 4}
6. The Print Functions ‘end’ Parameter
It is quite common to use a print statement without defining any of its optional parameters. Consequently, several Pythonistas are unaware that we can control the output to some degree. One optional parameter we can change is end. The end parameter specifies what should be shown at the end of a call to a print statement.
Example:
In this example, we will the the end parameter with the print function. Normally, the print()
adds a newline after each printed item. Without end=" "
, each language would appear on a new line. The end=" " ensures that each language is printed on the same line, separated by a space.
Python
a = ["english", "french", "spanish", "german", "twi"]
for language in a:
print(language, end=" ")
Outputenglish french spanish german twi
7. The Print Function ‘sep’ Parameter
We've shown different ways to display our formatted message. The sep parameter is an optional argument in the print() function that allows us to specify how objects should be separated if we include more than one.
Example:
In this example, we will see how we can display multiple object separated by specific characters.
Python
day = "04"
month = "10"
year = "2022"
print(day, month, year)
print(day, month, year, sep = "")
print(day, month, year, sep = ".")
Output04 10 2022
04102022
04.10.2022
8. Ternary Operator
The ternary operator is also referred to as a conditional expression among names. We use ternary operators to evaluate things based on whether a condition is True or False. This is a concise way to write a simple if-else statement in Python.
Example:
This code explains the use of a simple ternary operator in Python. Since condition is True, "John" gets assigned to name.
Python
condition = True
name = "John" if condition else "Doe"
print(name)
9. Remove Duplicates From Lists
The simplest way to remove duplicate elements from a list is to convert the list into a set.
Example:
Python
a = [1, 1, 2, 3, 4, 5, 5, 5, 6, 7, 2, 2]
print(list(set(a)))
Output[1, 2, 3, 4, 5, 6, 7]
10. Matching Regex
Regular expressions allow us to specify a pattern of text to search for; The majority of people know we can search for things using CTRL + F (Windows), but if we don't know the exact thing we're searching for, how could we find it? The answer is to search for patterns.
Regular expressions are a major time saver. If we were to code rules to catch the instances in our image instead of regex, it could take up to 10+ lines of code.
Example:
In this example, we will find all the occurrence of the word 'cat'.
Python
import re
# Define a simple text
text = "The cat is sitting on the mat with another cat."
# Define a regular expression pattern to find the word 'cat'
pattern = r"cat"
# Use re.findall() to find all occurrences of the pattern in the text
matches = re.findall(pattern, text)
# Output the results
print(f"Occurrences of 'cat': {matches}")
OutputOccurrences of 'cat': ['cat', 'cat']
11. Regex Pipe
Regular expressions have a special character called pipe (|) that allows us to match one of many expressions, and they can be used anywhere. This is super handy for when we've got several similar patterns.
Example:
This example, will find all the occurrence of the words that contains man, woman or human in them.
Python
import re
heros = re.compile(r"Super(man|woman|human)")
h1 = heros.search("This will find Superman")
h2 = heros.search("This will find Superwoman")
h3 = heros.search("This will find Superhuman")
print(h1.group())
print(h2.group())
print(h3.group())
OutputSuperman
Superwoman
Superhuman
12. Lambda Functions
The lambda keyword permits us to create small, restricted, anonymous functions in one line. They behave as a regular function declared with a def keyword, except these functions do not have a name.
Example:
Tn this example, we will use lambda function to calculate the square of a number.
Python
square_lambda = lambda x: x**2
print(f"Lambda function: {square_lambda(4)}")
OutputLambda function: 16
13. The ‘swapcase’ Method
The swapcase() method is applied to a string object to allow us to change the upper case letters to lower case and vice versa in a single line of code. There are not many use cases for the swapcase() method, but it is nice to know.
Example
Python
string = "SoMe RaNDoM sTriNg"
print(string.swapcase())
14. The ‘isalnum’ Method
Let's say we're creating a program that requires users to input a password, but it must have a combination of numbers and letters. We can do this in one line of code by calling the isalnum() on the string instance. The method checks if all the characters are part of the alphabet (A-Za-z) and numeric (0-9). A space or symbol (!#%$&? etc.) will return False.
Example:
In this example, we will check is a string has alpha-numeric characters.
Python
password = "ABCabc123"
print(password.isalnum())
15. Exception Handling
Exception handling in Python is a mechanism to handle runtime errors, ensuring that the program can deal with unexpected issues gracefully without crashing. Python uses try
, except
, else
, and finally
blocks to catch and manage exceptions.
Example:
In this example, we will check for division by zero error. If we input y = 0
, the code will add 1
to y
in the except
block and then perform the division without raising an error.
Python
def get_ratio(x:int, y:int) -> int:
try:
ratio = x/y
except ZeroDivisionError:
y = y + 1
ratio = x/y
return ratio
print(get_ratio(x=400, y=0))
16. Identifying the Differences in Lists
In Python, identifying the differences between two lists can be done efficiently using sets and then performing various operations on them, such as simple subtraction, symmetric difference operator (^) or symmetric_difference() method.
Example:
In this example, we will use different methods to to find elements that are in list_2 but not in list_1 and vice versa using Python sets.
Python
list_1 = [1, 3, 5, 7, 8]
list_2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
solution_1 = list(set(list_2) - set(list_1))
solution_2 = list(set(list_1) ^ set(list_2))
solution_3 = list(set(list_1).symmetric_difference(set(list_2)))
print(f"Solution 1: {solution_1}")
print(f"Solution 2: {solution_2}")
print(f"Solution 3: {solution_3}")
OutputSolution 1: [9, 2, 4, 6]
Solution 2: [2, 4, 6, 9]
Solution 3: [2, 4, 6, 9]
17. Args and Kwargs
The *args parameter permits us to pass a variable number of parameters to a function when it’s non-keyworded (i.e., the parameters we pass do not require an associated name). On the other hand, the **kwargs parameter enables us to pass an arbitrary number of keyworded parameters to a function.
Example:
Here is a simple example, to show the usage of *args and **kwargs.
Python
def some_function(*args, **kwargs):
print(f"Args: {args}")
print(f"Kwargs: {kwargs}")
some_function(1, 2, 3, a=4, b=5, c=6)
OutputArgs: (1, 2, 3)
Kwargs: {'a': 4, 'b': 5, 'c': 6}
18. List Comprehension
List comprehension is a concise way to create lists in Python. It provides a more readable and expressive way to construct lists compared to traditional methods like using loops. With list comprehensions, we can generate lists by applying an expression to each item in an iterable (like a list, tuple, or string) and optionally filtering elements using a condition.
Example:
Here is a simple example of creating a list of even numbers up to 10 using list comprehension.
Python
even_numbers = [x for x in range(10) if x % 2 == 0 and x != 0]
print(even_numbers)
19. Aliasing
When we assign one identifier to another identifier, we end up with two identifiers that reference the same object. This is a concept known as aliasing. Changes in one alias will affect the other. Sometimes this behavior is desired, but often, it catches us off guard.
One way around it is to refrain from aliasing when using mutable objects. Another solution could be to create a clone of the original object rather than a reference.
Example:
In this example, we demonstrate how variable assignment in Python creates references to the same object rather than making a copy of it.
Python
a = [1, 2, 3, 4 ,5]
b = a
# Change the 4th index in b
b[4] = 7
print(id(a))
print(id(b))
print(a) # Remember we did not explicitly make changes to a.
Output140287296591104
140287296591104
[1, 2, 3, 4, 7]
20. F-strings
Occasionally, we may need to format a string object; Python 3.6 introduced a cool feature called f-strings to simplify this process. It helps to understand how strings were formatted before the new release to appreciate the new method better.
Example:
This example, shows the usage of f-string.
Python
first_name = "John"
age = 19
print(f"Hi, I'm {first_name} and I'm {age} years old!")
OutputHi, I'm John and I'm 19 years old!
21. Standalone Underscore
Underscore (_) is a legal identifier in Python, thus, it's possible to use it to reference an object. But underscore also has another responsibility: to store the result of the last evaluation.
Example:
Python
22. Underscore Visual
Another way we could use the underscore is as a visual separator for digit grouping in integral, floating-point, and complex number literals – this was introduced in Python.
Example:
Python
number = 1_500_000
print(number)
23. __name__ == “__main__”
There's a high chance we've seen this syntax in several Python programs; Python uses a special name called "__main__" and sets it to an identifier called __name__ if the Python file being run is the main program.
Example:
Python
if __name__ == "__main__":
print("Read on to understand what is going on when you do this.")
OutputRead on to understand what is going on when you do this.
24. Enumerate
Enumerate() is a built-in function that adds a counter to an iterable (like a list, tuple, or string) and returns it as an enumerate object. This is useful when we need both the index and the value of items during iteration.
Example:
Python
for index, value in enumerate(['a', 'b', 'c']):
print(index, value)
25. Sorting with Key
The sorted() function and the .sort() method allow sorting lists (or other iterables) based on a specific criterion using the key parameter. The key parameter expects a function that returns a value that will be used for sorting.
Example
Python
people = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 20}]
sorted_people = sorted(people, key=lambda x: x['age'])
print(sorted_people)
Output[{'name': 'Bob', 'age': 20}, {'name': 'Alice', 'age': 25}]
26. Reversed Iteration
Reversed iteration allows us to iterate over a sequence (like a list, string, or tuple) in reverse order. Python provides the built-in reversed() function to accomplish this, returning an iterator that accesses elements from the last to the first.
Example:
This example, will print the list elements in reversed order.
Python
numbers = [1, 2, 3, 4, 5]
for num in reversed(numbers):
print(num)
27. Checking for Substring
Checking for a substring means determining whether a smaller string (substring) is present within a larger string. This is commonly done using the in keyword, which checks if a substring exists within another string.
Example:
Python
text = "Hello, world!"
if "world" in text:
print("Substring found!")
else:
print("Substring not found!")
28. Flatten a List of Lists
Flattening a list of lists means converting a list that contains other lists into a single list with all the elements from the inner lists.
Example:
Python
nested_list = [[1, 2], [3, 4], [5, 6]]
flattened_list = [item for sublist in nested_list for item in sublist]
print(flattened_list)
29. String Join
The join() method is used to concatenate the elements of an iterable (like a list or tuple) into a single string, with a specified separator between each element.
Example
Python
words = ['apple', 'banana', 'cherry']
result = '-'.join(words)
print(result)
Outputapple-banana-cherry
30. Unpacking
In Python, unpacking refers to the process of extracting values from iterable objects (like lists, tuples, or dictionaries) and assigning them to individual variables. This feature allows for cleaner, more readable code by enabling multiple variable assignments in a single statement.
Unpacking List and Tuples
We can unpack lists or tuples into individual variables.
Python
# Example with a tuple
coordinates = (10, 20)
x, y = coordinates
print(x)
print(y)
# Example with a list
colors = ["red", "green", "blue"]
r, g, b = colors
print(r)
Unpacking Dictionary
We can unpack dictionaries using the ** operator. This is commonly used to merge dictionaries or pass arguments to functions.
Python
# Example with dictionary unpacking
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
# Merging dictionaries
merged_dict = {**dict1, **dict2}
print(merged_dict)
Output{'a': 1, 'b': 3, 'c': 4}
Star Unpacking
The star (*
) operator allows us to capture remaining elements of an iterable into a list.
Python
# Example with star unpacking
numbers = [1, 2, 3, 4, 5]
first, *middle, last = numbers
print(first)
print(middle)
print(last)
Conclusion
Mastering Python involves learning a variety of powerful tricks that can improve code efficiency, readability, and functionality. Techniques like list comprehensions, lambda functions, using enumerate(), the key parameter in sorting, and leveraging built-in functions like zip(), reversed(), and join() can significantly enhance the way we write Python code. These tricks not only make our code more Pythonic but also help in solving problems more elegantly and concisely, ultimately leading to better, cleaner, and more maintainable code.