A collection of 50 Python tricks and tips, demonstrating efficient and elegant ways to use Python for various tasks.
Create a list of squares using list comprehension.
squares = [x**2 for x in range(10)]
# Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Assign multiple variables in a single line.
a, b, c = 1, 2, 3
# a = 1, b = 2, c = 3
Swap the values of two variables without a temporary variable.
a, b = b, a
# Values of a and b are swapped
Get the index and value in a loop.
for index, value in enumerate(['a', 'b', 'c']):
print(f"{index}: {value}")
# Output: 0: a, 1: b, 2: c
Create dictionaries using a similar syntax to list comprehensions.
squares_dict = {x: x**2 for x in range(5)}
# Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Similar to lists, but for sets.
evens_set = {x for x in range(10) if x % 2 == 0}
# Output: {0, 2, 4, 6, 8}
Check if any or all elements of a list meet a condition.
has_even = any(x % 2 == 0 for x in [1, 3, 5, 8])
all_positive = all(x > 0 for x in [1, 2, 3, 4])
# has_even = True, all_positive = True
Safely get a value from a dictionary.
d = {'a': 1, 'b': 2}
value = d.get('c', 3)
# value = 3, as 'c' is not in d
Iterate over two lists in parallel.
for name, age in zip(['Alice', 'Bob'], [24, 25]):
print(f"{name} is {age} years old")
# Output: Alice is 24 years old, Bob is 25 years old
Create small anonymous functions.
multiply = lambda x, y: x * y
# multiply(2, 3) returns 6
Use * and ** to unpack lists and dictionaries into function arguments.
def func(a, b, c):
return a + b + c
args = [1, 2, 3]
print(func(*args))
# Output: 6
Assign a value based on a condition in a single line.
x = 10
y = "Greater than 5" if x > 5 else "Less or equal to 5"
# y = "Greater than 5"
You can chain comparison operators for succinct logic.
x = 5
is_between = 1 < x < 10
# is_between = True
Easily count the frequency of elements in an iterable.
from collections import Counter
frequencies = Counter(['apple', 'banana', 'apple', 'orange', 'banana', 'apple'])
# frequencies = Counter({'apple': 3, 'banana':
2, 'orange': 1})
Assign parts of a list into separate variables and capture the rest in another variable.
a, *b, c = [1, 2, 3, 4, 5]
# a = 1, b = [2, 3, 4], c = 5
An else
block after a loop is executed only if the loop didn't end with a break
.
for i in range(3):
if i == 3:
break
else:
print("Loop ended without break")
# Prints "Loop ended without break"
Get the next item from an iterator, with an option to specify a default value if the iterator is exhausted.
my_iter = iter([1, 2, 3])
first = next(my_iter, 'No items')
# first = 1
The else
block in a try-except
construct is executed if no exception is raised in the try
block.
try:
value = int("123")
except ValueError:
print("Conversion failed")
else:
print("Conversion successful")
# Prints "Conversion successful"
Combine two lists into a dictionary using dictionary comprehension and zip
.
keys = ['a', 'b', 'c']
values = [1, 2, 3]
my_dict = {key: value for key, value in zip(keys, values)}
# my_dict = {'a': 1, 'b': 2, 'c': 3}
Flatten a list of lists into a single list.
nested_list = [[1, 2], [3, 4], [5, 6]]
flat_list = [item for sublist in nested_list for item in sublist]
# flat_list = [1, 2, 3, 4, 5, 6]
Remove duplicates while preserving order (works in Python 3.6+).
items = [1, 2, 2, 3, 3, 1, 4]
unique_items = list(dict.fromkeys(items))
# unique_items = [1, 2, 3, 4]
Create lists with repeated elements concisely.
repeated_list = [0] * 5
# repeated_list = [0, 0, 0, 0, 0]
Use slicing to remove elements from a list.
my_list = [1, 2, 3, 4, 5]
my_list[1:3] = []
# my_list = [1, 4, 5]
The itertools
module provides a variety of tools for efficient looping and iteration.
import itertools
for combination in itertools.combinations([1, 2, 3], 2):
print(combination)
# Prints (1, 2), (1, 3), (2, 3)
Efficiently concatenate strings from an iterable.
words = ['Hello', 'world']
sentence = ' '.join(words)
# sentence = "Hello world"
Merge two dictionaries.
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict1.update(dict2)
# dict1 = {'a': 1, 'b': 3, 'c': 4}
Reverse a list or create sublists with slicing.
my_list = [1, 2, 3, 4, 5]
reversed_list = my_list[::-1]
sub_list = my_list[1:4]
# reversed_list = [5, 4, 3, 2, 1], sub_list = [2, 3, 4]
Suppose you have a list of dictionaries representing books, and you
want to sort these books first by their 'year' in descending order and then by their 'title' in ascending order.
books = [
{'title': 'Book A', 'year': 2000},
{'title': 'Book B', 'year': 1995},
{'title': 'Book C', 'year': 2000},
{'title': 'Book D', 'year': 1995}
]
sorted_books = sorted(books, key=lambda x: (-x['year'], x['title']))
# Output: [{'title': 'Book A', 'year': 2000}, {'title': 'Book C', 'year': 2000}, {'title': 'Book B', 'year': 1995}, {'title': 'Book D', 'year': 1995}]
Use dictionary syntax to create nested dictionaries.
nested_dict = {'dict1': {'keyA': 'valueI'}, 'dict2': {'keyB': 'valueII'}}
# Output: {'dict1': {'keyA': 'valueI'}, 'dict2': {'keyB': 'valueII'}}
Clear a list using list slicing.
my_list = [1, 2, 3, 4, 5]
my_list.clear()
# my_list = []
Use a slice to assign multiple items to a list.
my_list = [1, 2, 4, 5]
my_list[1:3] = [7, 8, 9]
# my_list = [1, 7, 8, 9, 5]
Use isinstance
and Iterable
from collections.abc
to check if an object is iterable.
from collections.abc import Iterable
is_iterable = isinstance(my_list, Iterable)
# is_iterable = True
Use in
to check if an element exists in a list, string, set, or dictionary keys.
is_member = 'Hello' in words
# is_member = True
Create a list using list comprehension with a conditional filter.
even_squares = [x**2 for x in range(10) if x % 2 == 0]
# even_squares = [0, 4, 16, 36, 64]
Apply a function to each item of an iterable and return a list of the results.
squared = list(map(lambda x: x**2, range(10)))
# squared = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Filter elements of an iterable, returning only those for which the function returns True
.
even_numbers = list(filter(lambda x: x % 2 == 0, range(10)))
# even_numbers = [0, 2, 4, 6, 8]
Pair elements from two lists to create a dictionary.
keys = ['a', 'b', 'c']
values = [1, 2, 3]
my_dict = dict(zip(keys, values))
# my_dict = {'a': 1, 'b': 2, 'c': 3}
Reverse an iterable without altering the original data structure.
for item in reversed(range(1, 4)):
print(item)
# Prints 3, 2, 1
Check if any element of an iterable satisfies a certain condition.
has_positive = any(x > 0 for x in [-1, 0, 1, 2])
# has_positive = True
Check if all elements of an iterable satisfy a certain condition.
all_positive = all(x > 0 for x in [1, 2, 3])
# all_positive = True
Use a dictionary to store and call functions.
operations = {
'add': lambda x, y:
x + y,
'subtract': lambda x, y: x - y
}
result = operations['add'](5, 3)
# result = 8
Use defaultdict
to automatically assign default values to non-existent keys.
from collections import defaultdict
default_dict = defaultdict(int)
default_dict['key'] += 1
# default_dict = defaultdict(<class 'int'>, {'key': 1})
Create readable tuples with namedtuple
.
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
point = Point(1, 2)
x_coordinate = point.x
# x_coordinate = 1
Insert elements into a list using list slices.
my_list = [1, 2, 4]
my_list[2:2] = [3]
# my_list = [1, 2, 3, 4]
Combine multiple iterables into one.
combined = list(itertools.chain(range(3), range(4, 6)))
# combined = [0, 1, 2, 4, 5]
Group elements of an iterable based on a key function.
data = sorted([('type1', 1), ('type1', 2), ('type2', 1)], key=lambda x: x[0])
for key, group in itertools.groupby(data, key=lambda x: x[0]):
print(f"{key}: {list(group)}")
# Prints 'type1: [('type1', 1), ('type1', 2)]' and 'type2: [('type2', 1)]'
Create a slice object for slicing lists and other sequences.
my_slice = slice(2, 5)
sliced_list = my_list[my_slice]
# sliced_list = [3, 4]
Create a dictionary from an iterable with index-value pairs.
indexed_fruits = {index: fruit for index, fruit in enumerate(fruits)}
# indexed_fruits = {0: 'apple', 1: 'banana', 2: 'cherry'}
Find the minimum or maximum item in a collection based on a key function.
oldest_book = max(books, key=lambda x: x['year'])
# oldest_book = {'title': 'Book B', 'year': 1995}
Sort a collection based on a custom key function.
sorted_by_title = sorted(books, key=lambda x: x['title'])
# sorted_by_title = [{'title': 'Book A', 'year': 2000}, {'title': 'Book B', 'year': 1995}, {'title': 'Book C', 'year': 2000}, {'title': 'Book D', 'year': 1995}]