An A-Z of useful Python tricks

Venkat
6 min readJan 15, 2023

--

Whether you’re new to programming or a seasoned veteran, Python offers a wealth of features that can help you write better, more efficient code.

In this blog post, we will explore some of the most useful Python tricks, organized alphabetically, that every developer should know.

A — any() and all(): These built-in functions are used to check if any or all elements of an iterable are true. The any() function returns True if at least one element is true, while the all() function returns True only if all elements are true.

numbers = [1, 3, 5, 0, 2]
# any()
print(any(numbers)) # True
# all()
print(all(numbers)) # False

B — bin(): This built-in function is used to convert an integer to its binary representation.

x = 10
print(bin(x)) # '0b1010'

C — zip(): This built-in function is used to combine two or more iterables into one. It creates an iterator that aggregates elements from each of the input iterables.

names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
# zip()
combined = zip(names, ages)
print(list(combined)) # [("Alice", 25), ("Bob", 30), ("Charlie", 35)]

D — del: This keyword is used to delete a variable or an item from a list.

x = 10
del x # x is deleted
numbers = [1, 2, 3, 4, 5]
del numbers[2] # the element at index 2(3) is deleted from the list

E — enumerate(): This built-in function is used to iterate over a sequence and keep track of the index. It returns an iterator that generates tuples containing the index and the corresponding element of the sequence.

numbers = [1, 2, 3, 4, 5]
# enumerate()
for i, n in enumerate(numbers):
print(i, n)
# Output: (0, 1), (1, 2), (2, 3), (3, 4), (4, 5)

F — filter(): This built-in function is used to filter elements from an iterable based on a certain condition. It returns an iterator that only generates the elements that satisfy the condition.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# filter()
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers)) # [2, 4, 6, 8, 10]

G — globals() and locals(): These built-in functions are used to access the global and local variables of a program. globals() returns a dictionary of the global variables, while locals() returns a dictionary of the local variables.

x = 10
y = 20
# globals()
print(globals()) # {'__name__': '__main__', 'x': 10, 'y': 20, ...}
# locals()
def my_function():
z = 30
print(locals()) # {'z': 30}
my_function()

H — hash(): This built-in function is used to get the hash value of an object. The hash value is an integer that is unique for each object, and it is used to identify the object in a dictionary or set.

x = "hello"
print(hash(x)) # -1010901246529012858

I — isinstance(): This built-in function is used to check if an object is an instance of a certain class or a subclass of it. It returns True if the object is an instance of the class, and False otherwise.

class MyClass:
pass
x = MyClass()
# isinstance()
print(isinstance(x, MyClass)) # True
print(isinstance(x, str)) # False

J — join(): This string method is used to join a sequence of strings with a certain separator.

words = ["Python", "is", "awesome"]
# join()
sentence = " ".join(words)
print(sentence) # "Python is awesome"

K — keys(): This dictionary method is used to get a view of the keys of a dictionary.

my_dict = {"name": "Alice", "age": 25, "city": "New York"}
# keys()
print(my_dict.keys()) # dict_keys(['name', 'age', 'city'])

L — len(): This built-in function is used to get the length of an object. It works with strings, lists, tuples, sets, and dictionaries.

my_list = [1, 2, 3, 4, 5]
# len()
print(len(my_list)) # 5

M — map(): This built-in function is used to apply a certain function to all elements of an iterable. It returns an iterator that generates the results of the function applied to each element.

numbers = [1, 2, 3, 4, 5]
# map()
squared_numbers = map(lambda x: x ** 2, numbers)
print(list(squared_numbers)) # [1, 4, 9, 16, 25]

N — next(): This built-in function is used to get the next item from an iterator.

numbers = [1, 2, 3, 4, 5]
# next()
iterator = iter(numbers)
print(next(iterator)) # 1
print(next(iterator)) # 2

O — ord(): This built-in function is used to get the Unicode code point of a character.

x = "A"
print(ord(x)) # 65

P — pow(): This built-in function is used to raise a number to a certain power.

x = 2
y = 3
# pow()
print(pow(x, y)) # 8

Q — quitting and quit(): This built-in function is used to quitting the program.

#quit()
for i in range(10):
if i == 5:
print(quit)
quit()
print(i)

R — range(): This built-in function is used to generate a range of integers.

# range()
for i in range(5):
print(i)
# Output: 0, 1, 2, 3, 4

S — sorted(): This built-in function is used to sort a list or any other iterable. It returns a new list containing all elements from the original list in a sorted order.

numbers = [3, 1, 5, 2, 4]
# sorted()
sorted_numbers = sorted(numbers)
print(sorted_numbers) # [1, 2, 3, 4, 5]

T — type(): This built-in function is used to get the type of an object.

x = "hello"
# type()
print(type(x)) # <class 'str'>

U — uppper() and lower(): These string methods are used to convert a string to uppercase or lowercase.

x = "Hello World"
# upper()
print(x.upper()) # "HELLO WORLD"
# lower()
print(x.lower()) # "hello world"

V — vars(): This built-in function is used to get the __dict__ attribute of an object.

class MyClass:
x = 10
y = 20
obj = MyClass()
# vars()
print(vars(obj)) # {'x': 10, 'y': 20}

W — while loop: This loop is used to repeatedly execute a block of code as long as a certain condition is true.

i = 0
# while loop
while i < 5:
print(i)
i += 1
# Output: 0, 1, 2, 3, 4

X — xor operator: This operator is used to perform a bitwise exclusive or operation on two numbers.

x = 5
y = 3
# xor operator
print(x ^ y) # 6

Y — yield keyword: This keyword is used in a function to create a generator. A generator is an iterable that generates values on the fly, instead of creating a list in memory.

def my_generator():
yield 1
yield 2
yield 3
gen = my_generator()
print(next(gen)) # 1
print(next(gen)) # 2
print(next(gen)) # 3

Z — zip(): We already talked about this function in letter C, that this built-in function is used to combine two or more iterables into one.

In conclusion, these are just a few examples of the many useful Python tricks that exist. The language has a vast ecosystem of libraries and tools that can help you with any task you need to accomplish.

From web development to data analysis to machine learning, Python has something to offer for everyone.

It’s always a good idea to keep expanding your knowledge of the language, by learning new tricks and techniques, keeping updated with the latest developments and trends in the industry, and participating in the vibrant Python community.

With practice and dedication, you will be able to master Python, and take your coding skills to the next level.

I hope this blog post has helped you to discover some new and interesting Python tricks that you can start using in your projects.

Remember, the best way to learn a programming language is by writing code, so don’t hesitate to try these tricks out for yourself and see how they work. Happy coding!

--

--

Venkat

I enjoy exploring new technologies and sharing my knowledge through writing.