5 Python Features to Make Your Code More Advanced

Enhance your Python🐍 skills

Aleksei Rozanov
6 min readJul 11, 2024
Photo by Kevin Ku on Unsplash

Python has been my main programming tool for the last 2 years, and I’m sure it will stay the one for years, despite the fact that I have some basic knowledge of C++, JS, MatLab and R. The reason for that is its user-friendliness, intuitiveness and, of course, the quality and popularity of the machine learning frameworks built in python. However, although the internet is full of educational materials and tutorials to learn this language, I comprehended some of its features by myself when feeling an urgent need to optimize the code or to implement something new.

So in this article I want to show you 5 unique features of python, which I wish I’d known when I was starting my journey. These features can be used by anyone, even beginners, to make their code more professional, efficient and good-looking.

1. Lists

Of course we will start with lists, since these are one of the basic data structures in python. You can initialize a list in two ways:

l = list()
l = []

Often we need to fill a list iteratively. In the vanilla set up (like in many other programming languages), you can use the for loop:

for i in range(10):
l.append(i)

Or we can even created a nested loop:

L = []
for i in range(10):
l = []
for j in range(5):
l.append(i)
L.append(l)

But this code looks clumsy. It took us 5 rows to implement quite simple idea…

Let’s use the first python feature:

l = [i for i in range(10)]
l = [[i for _ in range(5)] for i in range(10)]

As you can see it took only 2 rows for 2 loops. This is the true beauty of python.

2. Sets

Arguably, sets are one of the least known data structures. But they have one unique feature, which I use extensively in my projects. Imagine you have a list with duplicates. To my knowledge, by July 2024 in python there is no built-in function to drop them. Instead of using dictionary’s keys or something else to tackle this problem, just transform you list to a set and then back to a list:

l = [1,1,2,2,3,4,5,0]
l = list(set(l))

Super simple and efficient. Not only does it drop duplicates, but it also sorts your list!

3. Dynamic typing

If you’ve written at least one Python program, you must know that there is no such thing as a variable type declaration. When you type a = 42.2, you don't specify float32 or float64; you just assign the value. It works because Python is based on dynamic typing, meaning all the variable types are defined during runtime. This is important when we start talking about memory!

There are mutable and immutable objects in python. The value of mutable objects (list, dict, set) can be changed over time. For instance:

l = [1,2,3]
l[0] = 'a'

Whereas immutable objects (None, bool, int, float, complex, str, tuple) do not allow you to change their value. Let’s create variable a and check its ID in the memory. If we change its value, then we’ll get a new ID:

It means that a in this case, can be considered as a pointer to an object in the computer memory. In this example, 10 and 20 are stored as different objects.

But why am I writing all of this? Because there is a pitfall that has caused me severe pain several times, and I want you to be aware of it. Let’s do an experiment by creating a list p and then assigning its value to a new variable P:

Now let’s append the list P and print the results:

You can see now that we appended not only P, but also the first list p. Let’s check their ID as we did before:

They are identical. Both variables pand Ppoint to the same object. This python feature has caused me tons of confusion. So if you want to assign the same value of list p to a new list, I recommend to use the copy function.

In this case you won’t mess up your code!

P.s. If we try to do the same thing with integers, for instance, by adding 10 istead of appending, we will get a new object with a new ID:

4. Assertion

Often in our code we use conditions before doing anything to check if we are about to process the data we need. In such situations the code can become clumsy as well:

A = [1,0,0,16]
B = [23,32,2,4]
for a,b in zip(A,B):
if a==b**2:
print(a,b, 'Error!')

To avoid that you can use the assert keyword. It allows you to put a logical sentence and an error string in one line of code, making it much more appealing!

As you can see, when the assertion is failed, python shows an assertion error with a custom message which you can compose yourself.

5. Packing

When I was starting, those stars (* and **) before arguments were really confusing. But it turned out that they might help you a lot when your function has a lot of variables to pass.

Let’s write a function with 2 values to pass and 3 default values. This function will perform simple math calculations:

def F(a, b, c=3, d=1, k=1):
return (a*b*c/d)**k

At some point, we might want to pass only a and b:

But imagine that you want to also pass a and d, but you don’t know the names of these variables (they are simply hidden from you). Then you can use positional arguments (often args):

In the case of args, the order always matters! If you change it, the results will be different (since args is a list):

Now imagine a different situation. You know the names of the variables, but you have no clue about their order. Then keyword arguments (or often kwargs) will help you:

Since kwargs is a dictionary you can use any order you want, the results will stay the same.

===========================================

That’s it! I hope that the article has a little bit extended your understanding of python and from now on you’ll be using these features extensively and consciously.

Would you like to see more python features in the next article?:)

===========================================

All my publications on Medium are free and open-access, that’s why I’d really appreciate if you followed me here!

P.s. I’m extremely passionate about (Geo)Data Science, ML/AI and Climate Change. So if you want to work together on some project pls contact me in LinkedIn.

🛰️Follow for more🛰️

--

--

Aleksei Rozanov

🎓 M.s. Big Data and ML | 👩🏻‍💻AI/ML + 🌍 Geo data + 🛰️Remote sensing