3 Common Mistakes You’d Want to Avoid in Python

Three problems and their solutions

Halil Yıldırım
Sep 30 · 2 min read
Photo by NeONBRAND on Unsplash

In this piece, I will talk about three common mistakes you wouldn’t want to do!


The Problem: Default Mutable Object

Hey, wait—what is a mutable object in Python? Mutable objects are objects you can change. List, set, and dict are examples of mutable objects.

For the sake of argument, I will define a very simple and useless function.

def add(x, y=[]):
y.append(x)
return y

In this function, we set the variable to a list(mutable object) as a default. Let’s use this function.

def add(x, y=[]):
y.append(x)
return y


print(add('halil'))
print(add('yıldırım'))

The output is :

What is going on here? It’s overwriting the same list. When we first called , the default argument became and started overwriting the same list. Let’s see:

def add(x, y=[]):
y.append(x)
return y


add('halil')
print(add.__defaults__)
add('yıldırım')
print(add.__defaults__)

The output is:

As you can see, we are overwriting the default list.


The Solution: Default Mutable Object

Instead of passing mutable object as a default argument, you should pass . The example:

def add(x, y=None):
if y is None:
y = list()
y.append(x)
else:
y.append(x)
return y


print(add('halil'))
print(add('yıldırım'))

The output:


The Problem: Copy

Let’s create a dictionary in Python.

a = {'a': 5, 'b': 4, 'c': 8}

Let’s set to :

a = {'a': 5, 'b': 4, 'c': 8}
b = a

Let’s delete the first element with the key .

del b['a']

Let’s write a, b and see what’s going on.

a = {'a': 5, 'b': 4, 'c': 8}
b = a
del b['a']
print(b)
print(a)

The output:

What is going on here? We just intended to delete the first element of b, not a …


The Solution: Copy

When you say b = a, you basically say and are pointing the same object. If both are pointing the same object, it doesn’t matter if you do some operations with or . Both will affect this object.

A solution:

import copy
a = {'a': 5, 'b': 4, 'c': 8}
b = copy.copy(a)
del b['a']
print(b)
print(a)

The output:


The Problem and Solution: Naming Your file

Never name your python file with the libraries you are going to use.

For instance, if you name your file , your program will get confused about what you’re trying to do.

import random

print(random.random())

The output:

Check my GitHub respiratory and star it. you can find useful python codes which I update as much as I can.

Better Programming

Advice for programmers.

Halil Yıldırım

Written by

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade