Python “tricks” I can not live without

Sebastian Opałczyński
Level Up Coding
Published in
7 min readJan 12, 2021

--

It’s python.

There is plenty of similar articles on the web, but I just thought that I can add my perspective on the topic, and make the “tricks” list more complete. The code fragments used here are somehow crucial to my workflow and I am reusing them over and over again.

Sets

It’s often the case that developers tend to forget that python has set datatype and trying to use lists for everything. What is set? Well, long story short:

A set is an unordered collection with no duplicate elements.

If you get familiar with sets and their logic it can solve a lot of problems for you. For example — how to get all of the unique letters used in a word?

myword = "NanananaBatman"
set(myword)
{'N', 'm', 'n', 'B', 'a', 't'}

Boom. Problem solved, but to be honest it’s from the official python documentation, so nothing surprising.

What about this? Get a list of items without element repetition?

# first you can easily change set to list and other way aroundmylist = ["a", "b", "c", "c"]# let's make a set out of itmyset = set(mylist)# myset will be:
{'a', 'b', 'c'}
# and, it's already iterable so you can do:
for element in myset:
print(element)
# but you can also convert it to list again:
mynewlist = list(myset)
# and mynewlist will be:
['a', 'b', 'c']

As you can see the repeating “c” is not the case anymore. Only one thing you should be aware of is that the order of elements between mylist and mynewlist can be different:

mylist = ["c", "c", "a", "b"]
mynewlist = list(set(mylist))
# mynewlist is:
['a', 'b', 'c']
# as you can see it's different order;

But! We can go deeper.

Imagine the case that you have a one to many relation between some entities, to make it more concrete — user and permissions; usually, it’s the case that one user can have multiple permissions. Now imagine that someone wants to modify multiple permissions — adding some and removing some at the same time, how…

--

--

Software engineer, technology enthusiast, common sense lover, serial co-founder, and a father of three.