VOOZH about

URL: https://www.analyticsvidhya.com/blog/2021/06/if-you-are-a-python-programmer-avoid-these-mistakes/

โ‡ฑ Python Mistakes | Common Mistakes in Python You Should Avoid


India's Most Futuristic AI Conference Is Back โ€“ Bigger, Sharper, Bolder

  • d
  • :
  • h
  • :
  • m
  • :
  • s

If You Are A Python Programmer, Avoid These Mistakes!

Gaurav Sharma Last Updated : 01 Jul, 2021
5 min read

This article was published as a part of the Data Science Blogathon

Introduction

Python is a simple and easy-to-learn programming language. But still some programmers especially newer ones to the language get mislead. Many programmers have experience with core programming languages like Java, C++, or C#. So they are used to doing it the hard way and when they use this python language which is with easy syntax they misinterpret the diversity and power of Python and sometimes end up surrounded with errors.

๐Ÿ‘ Python Mistakes

Source: Google Images

In this article, I will try to put forward those mistakes. This article can be read by any python developer who is at a basic or intermediate level. There are some very common errors like typos, pythonโ€™s case sensitivity, ignoring Indentation, not using colons for compound statements. These are basic errors that almost everyone is familiar with. We will look at some more errors in detail.

So, letโ€™s get started!

1. Modifying a list while iterating over it

This is a problem faced by almost every python programmer at least once in their coding journey.

Look at this code below:

odd = lambda x : bool(x % 2)
numbers = [n for n in range(20)]
for i in range(len(numbers)):
 if odd(numbers[i]):
 del numbers[i] # Deleting item from a list while iterating over it

Error:

Traceback (most recent call last):
 	 File "<stdin>", line 2, in <module>
IndexError: list index out of range

This problem is obvious but still, sometimes programmers do this. So, the solution to this problem is to use list comprehensions. They are very useful in this kind of situation.

By using list comprehension:

odd = lambda x : bool(x % 2)
numbers = [n for n in range(20)]
numbers[:] = [n for n in numbers if not odd(n)]
print(numbers)

Output:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

2. Misuse of expressions as defaults for function arguments

This is one of those errors which are hard to debug because it does not give any error and works fine in almost all cases. But this can cause you trouble in complex workspaces.  When we specify a mutable optional function argument this error occurs. Look at the code below to understand better.

def myFunc(myArr=[]):
 myArr.append("Hello")
 return myArr

This is a simple function that would append โ€œHelloโ€ at the end of the list given to it otherwise it will return [โ€œHelloโ€] whenever it is invoked without myArr argument. But we get something else, look at it:

Output:

>>>myFunc()
["Hello"]
>>>myFunc()
["Hello", "Hello"]
>>>myFunc()
["Hello", "Hello", "Hello"]

I hope you got it, this is not the output we were expecting. But since this piece of code doesnโ€™t give any error most of the developers could get away with this if not noticed. Letโ€™s understand this.

In python, the default arguments are evaluated only once. On the first call, it worked fine but on the next calls (second, third) it used the existing myArr instead of initializing it again. So, to solve this:

def myFunc(myArr=None):
 if myArr is None:
 myArr=[]
 myArr.append("Hello")
 return myArr

Output:

>>>myFunc()
["Hello"]
>>>myFunc()
["Hello"]

3. Class variables used incorrectly

Letโ€™s look at this example:

class temp1(obj):
 t=5
class temp2(temp1):
 pass
class temp3(temp1):
 pass
print( temp1.t, temp2.t, temp3.t)

Output

5
5
5

This looks good.

Now if,

temp2.t = 2
print( temp1.t, temp2.t, temp3.t)

Output

5
2
5

This is also fine.

Now if I change the value of class temp1 look what happens:

temp1.t = 3
print( temp1.t, temp2.t, temp3.t)

Output

3
2
3

Boom! Value of class temp3 also changed. But this is not what we wanted. In python, the class variable is internally handled as dictionaries and follows an order known as Method Resolution Order. This happened because variable t was not present in class temp3 so it was looked up in the base class which is temp1. Hence we got this output.

4. Often trying to reinvent the wheel

Programmers coming from low-level language backgrounds like C++, C, etc. try to write everything from scratch. You might be aware that the python community is quite large, here every problem has a solution(seriously). Here we are discussing basic things that python offers. Some of those are related to using of decorators, generators, sort functions, etc. People often write custom sort function which is not needed. It just makes your code length and messy. To make your code more elegant use this:

list.sort(key = , reverse = )

We can sort tuples, dictionaries, or any python object with this. So, it can be used in almost every scenario. Look at these examples:

numbers = [4,5,2,18,3]
numbers.sort(reverse=True)
print("Sorted numbers in Decreasing order:", numbers)

Output:

Sorted numbers in Decreasing order: [18, 5, 4, 3, 2]

With a list of tuples:

#take second element for sort
def second(elem):
 return elem[1]

#random list
myList = [('a', 2), ('r', 4), ('t', 1), ('g', 3)]

# sort list with key
myList.sort(key=second)

# print list
print('Sorted :', myList)

Output:

Sorted list: [('t', 1), ('a', 2), ('g', 3), ('r', 4)]

5.Misusing The __init__ Method

The init is a reserved method in python classes that are used as constructors. It is invoked when Python allocates memory to a new class object or when an object is created from a class and it allows the class to initialize the attributes of the class. It is used to set the values of instance members for the class object. But programmers sometimes use it to return a value from the init method which is not the actual purpose of the init method. So, do take care of this.

6. Using assert statement as guarding condition

Assert provides an easy way to check any condition and fail execution if needed. So, developers use it frequently to check validity. But assert statements are recommended to be used only in tests. Let me explain to you why. When the python interpreter is invoked with the -o flag(optimize), the assert statements are deleted from the bytecode. So, if you have used assert statements in production code to validate something that block wonโ€™t be executed at all. This opens up a security threat. Hence, consider it using only in tests.

Incorrect:

assert re.match(VALID_EMAIL_REGEXP, email) is not None

Correct:

if not re.match(VALID_EMAIL_REGEXP, email):
 raise AssertionError

7.Unnecessary lambda expression

Functions in Python are the aggregation of related statements designed to perform a computational, logical task. Functions can be directly assigned to any variable, can be passed as an argument in another function, and so on. But this may not be intuitive for programmers coming from other programming languages.

Example:

def request(self, method, **kwargs):
 if method not in ("put", "post"):
 req.get_method = lambda: method.upper()

Better way:

def request(self, method, **kwargs):
 if method not in ("put", "post"):
 req.get_method = method.upper

End Notes

These are some common mistakes done by newcomers. Familiarize yourself more with the key nuances of Python, it will for sure help you optimize the use of the language while avoiding some of its more common errors.

I hope you find the pointers in this article helpful. Letโ€™s connect on Linkedin. Thanks for reading if you reached here :).

Happy coding!

The media shown in this article are not owned by Analytics Vidhya and are used at the Authorโ€™s discretion.

Love Programming, Blog writing and Poetry

Login to continue reading and enjoy expert-curated content.

Free Courses

Generative AI - A Way of Life

Explore Generative AI for beginners: create text and images, use top AI tools, learn practical skills, and ethics.

Getting Started with Large Language Models

Master Large Language Models (LLMs) with this course, offering clear guidance in NLP and model training made simple.

Building LLM Applications using Prompt Engineering

This free course guides you on building LLM apps, mastering prompt engineering, and developing chatbots with enterprise data.

Improving Real World RAG Systems: Key Challenges & Practical Solutions

Explore practical solutions, advanced retrieval strategies, and agentic RAG systems to improve context, relevance, and accuracy in AI-driven applications.

Microsoft Excel: Formulas & Functions

Master MS Excel for data analysis with key formulas, functions, and LookUp tools in this comprehensive course.

Responses From Readers

Flagship Programs

GenAI Pinnacle Program| GenAI Pinnacle Plus Program| AI/ML BlackBelt Program| Agentic AI Pioneer Program

Free Courses

Generative AI| DeepSeek| OpenAI Agent SDK| LLM Applications using Prompt Engineering| DeepSeek from Scratch| Stability.AI| SSM & MAMBA| RAG Systems using LlamaIndex| Building LLMs for Code| Python| Microsoft Excel| Machine Learning| Deep Learning| Mastering Multimodal RAG| Introduction to Transformer Model| Bagging & Boosting| Loan Prediction| Time Series Forecasting| Tableau| Business Analytics| Vibe Coding in Windsurf| Model Deployment using FastAPI| Building Data Analyst AI Agent| Getting started with OpenAI o3-mini| Introduction to Transformers and Attention Mechanisms

Popular Categories

AI Agents| Generative AI| Prompt Engineering| Generative AI Application| News| Technical Guides| AI Tools| Interview Preparation| Research Papers| Success Stories| Quiz| Use Cases| Listicles

Generative AI Tools and Techniques

GANs| VAEs| Transformers| StyleGAN| Pix2Pix| Autoencoders| GPT| BERT| Word2Vec| LSTM| Attention Mechanisms| Diffusion Models| LLMs| SLMs| Encoder Decoder Models| Prompt Engineering| LangChain| LlamaIndex| RAG| Fine-tuning| LangChain AI Agent| Multimodal Models| RNNs| DCGAN| ProGAN| Text-to-Image Models| DDPM| Document Question Answering| Imagen| T5 (Text-to-Text Transfer Transformer)| Seq2seq Models| WaveNet| Attention Is All You Need (Transformer Architecture) | WindSurf| Cursor

Popular GenAI Models

Llama 4| Llama 3.1| GPT 4.5| GPT 4.1| GPT 4o| o3-mini| Sora| DeepSeek R1| DeepSeek V3| Janus Pro| Veo 2| Gemini 2.5 Pro| Gemini 2.0| Gemma 3| Claude Sonnet 3.7| Claude 3.5 Sonnet| Phi 4| Phi 3.5| Mistral Small 3.1| Mistral NeMo| Mistral-7b| Bedrock| Vertex AI| Qwen QwQ 32B| Qwen 2| Qwen 2.5 VL| Qwen Chat| Grok 3

AI Development Frameworks

n8n| LangChain| Agent SDK| A2A by Google| SmolAgents| LangGraph| CrewAI| Agno| LangFlow| AutoGen| LlamaIndex| Swarm| AutoGPT

Data Science Tools and Techniques

Python| R| SQL| Jupyter Notebooks| TensorFlow| Scikit-learn| PyTorch| Tableau| Apache Spark| Matplotlib| Seaborn| Pandas| Hadoop| Docker| Git| Keras| Apache Kafka| AWS| NLP| Random Forest| Computer Vision| Data Visualization| Data Exploration| Big Data| Common Machine Learning Algorithms| Machine Learning| Google Data Science Agent
๐Ÿ‘ Av Logo White

Continue your learning for FREE

Forgot your password?
๐Ÿ‘ Av Logo White

Enter OTP sent to

Edit

Wrong OTP.

Enter the OTP

Resend OTP

Resend OTP in 45s

๐Ÿ‘ Popup Banner
๐Ÿ‘ AI Popup Banner