Python Common Mistakes

7 Common Python Beginner Mistakes. What Should You Not Do?

There are common Python mistakes that beginner developers make. In this tutorial we will cover a few so you know what not to do in your code.

Common Python mistakes when you are getting started with coding are: not using the correct indentation, forgetting colons at the end of certain lines of code, using variables before assigning a value to them. Other examples of errors are trying to change immutable objects and trying to modify a list while iterating through it.

These are some of the errors I will explain in this tutorial (and not only).

So, let’s begin!

1. Is Correct Indentation Always Required in Python?

Correct indentation is a must in Python. Incorrect indentation in a Python program represents a syntax error.

You might not be used to it if you come from a different programming language that doesn’t enforce indentation in the same way Python does.

Let’s take, for example, the following code:

for i in range(10):
print("The next number is", i)

The Python interpreter will throw an exception because the print statement inside the for loop has to be indented.

  File "python_common_mistakes.py", line 2
    print("The next number is", i)
    ^
IndentationError: expected an indented block

Wait…

But we said that an indentation error is a syntax error.

We can confirm that the exception type IndentationError is a subclass of SyntaxError (it’s basically a type of syntax error).

We will use the issubclass() built-in function:

>>> issubclass(IndentationError, SyntaxError)
True

The Python interpreter returns a boolean with value True that confirms that IndentationError is a type of SyntaxError.

To fix this error indent the print statement (this is something that Python IDEs will help you with).

for i in range(10):
    print("The next number is", i)

[output]
The next number is 0
The next number is 1
The next number is 2
The next number is 3
The next number is 4
The next number is 5
The next number is 6
The next number is 7
The next number is 8
The next number is 9

Fixed!

2. Does an If Statement Need a Colon in Python?

Yes, a colon is required at the end of the header (first line) of a Python if statement. Missing the colon will cause a syntax error.

Let’s go through an example…

Write a basic if statement that prints a message depending on the value of the variable x.

x = 10

if x < 20
    print("x is lower than 20")
else:
    print("x is greater than 20")

When you run this code you get back the following error:

  File "python_common_mistakes.py", line 3
    if x < 20
            ^
SyntaxError: invalid syntax

As mentioned before the syntax error is caused by the fact that I have forgotten to add a colon ( : ) at the end of the first line of the if statement, the one that contains the if keyword.

Below you can see the correct code:

x = 10

if x < 20:
    print("x is lower than 20")
else:
    print("x is greater than 20")

And this time the output is correct:

x is lower than 20

Makes sense?

3. Can You Use a Variable Before Assigning a Value to It?

Create a for loop that reads all the numbers from a list called numbers and appends the numbers that are greater than 2 to a new list called updated_numbers.

numbers = [1, 2, 3, 4, 5]

for number in numbers:
    if number > 2:
        updated_numbers.append(number)

print(updated_numbers)

This code throws the following NameError exception:

Traceback (most recent call last):
  File "python_common_mistakes.py", line 5, in <module>
    updated_numbers.append(number)
NameError: name 'updated_numbers' is not defined

That’s because we haven’t assigned a value to the updated_numbers list before using it in the for loop.

Assign an empty list to it and see what happens…

numbers = [1, 2, 3, 4, 5]
updated_numbers = []

for number in numbers:
    if number > 2:
        updated_numbers.append(number)

print(updated_numbers)

The output returned is correct.

[3, 4, 5]

We have fixed the error in our code by setting the updated_numbers list to an empty list before the for loop.

Great!

4. How Do You Modify an Immutable Python Object?

This is a common Python mistake…

You cannot modify an immutable object in Python. That’s the reason why it’s called immutable as opposed to mutable (an object that can be modified).

In Python there are data types that are mutable (they can be updated) and data types that are immutable (they cannot be updated).

For example, a list is mutable and we can modify its elements:

animals = ['tiger', 'lion', 'giraffe']

animals.append('dolphin')
print(animals)

animals[0] = 'shark'
print(animals)

[output]
['tiger', 'lion', 'giraffe', 'dolphin']
['shark', 'lion', 'giraffe', 'dolphin']

Here we have first appended the string ‘dolphin’ to the animals list and then we have updated the first element of the list (index zero).

A common error is trying to do the same with a tuple that is an immutable data type.

Here is our tuple…

animals = ('tiger', 'lion', 'giraffe')

Note: the only difference in the way a list and a tuple are represented is the square brackets (list) vs parentheses (tuple).

This is the result…

When you append a string to the tuple animals you get back the following:

animals.append('dolphin')
print(animals)

[output]
Traceback (most recent call last):
  File "python_common_mistakes.py", line 3, in <module>
    animals.append('dolphin')
AttributeError: 'tuple' object has no attribute 'append'

A tuple has no method append because it’s immutable and for this reason new items cannot be added to it.

Also…

If you assign a value to one of its element the Python interpreter throws the following exception:

animals[0] = 'shark'
print(animals)

[output]
Traceback (most recent call last):
  File "python_common_mistakes.py", line 3, in <module>
    animals[0] = 'shark'
TypeError: 'tuple' object does not support item assignment

The TypeError “object does not support item assignment” is telling us that tuples are immutable. In other words you cannot update the value of items in a tuple.

You might be wondering, what’s the point of having tuples if you cannot modify them?

If you have questions like this one have a look at this article I have written about Python tuples.

5. Does a Python For Loop Always Need an Index?

In the code below we are using the index i to access the items of the list cities.

This is not really required considering that we are only using the index i to access elements of the list and we don’t need it for any other reason inside our for loop.

cities = ['London', 'New York', 'Paris', 'Rome']

for i in range(len(cities)):
    print(cities[i])

[output]
London
New York
Paris
Rome

It’s easier to use a for loop in which Python handles indexing for you.

for city in cities:
    print(city)

[output]
London
New York
Paris
Rome

Can you see that the output is exactly the same?

This has also two advantages:

  • It makes your code more readable (no need to think about the range and len functions).
  • It prevents errors due to trying to manage indexes in your code. Especially when the code inside the for loop becomes more complex.

In essence…

In a Python for loop you don’t always need an index. By default Python can handle indexing transparently to make your code easier to write and read. You would only use an index in a for loop if you absolutely need that index in the logic of your code.

6. Are Python Equality and Assignment Operators Different?

A common mistake is to confuse the Python equality operator with the assignment operator.

Let me explain…

Python provides one operator to assign values to variables (assignment operator) and one operator to verify if variables have the same value (equality operator).

When you are getting started with Python you might confuse those two operators and use them in the wrong part of your code.

day = "Monday"

if day = 'Tuesday':
    print("Today is Tuesday")
else:
    print("Today is not Tuesday")

When you execute this code…

…the Python interpreter returns a syntax error because we are using the assignment operator instead of the equality operator when we check if the variable day is equal to ‘Tuesday’.

  File "python_common_mistakes.py", line 5
    if day = 'Tuesday':
           ^
SyntaxError: invalid syntax

Note: Python IDEs will highlight this as an error but you will not see that if you use a simple text editor.

Let’s replace = with == in the header of the if statement.

day = "Monday"

if day == 'Tuesday':
    print("Today is Tuesday")
else:
    print("Today is not Tuesday")

[output]
Today is not Tuesday

This code works fine now that we are using the equality operator in the header of the if statement.

Good job!

7. Can I Modify a Python List While Iterating Through It?

Not really…

For example, a common error is to remove an item from a list while iterating through it.

Here is what happens if you write a for loop that accesses the items of a list using their index and then you try to remove an item from that list inside the for loop.

fruits = ['orange', 'apple', 'banana']

for i in range(len(fruits)):
    if fruits[i].startswith('o'):
        fruits.remove(fruits[i])
    print(fruits[i])

Python throws a IndexError exception.

apple
banana
Traceback (most recent call last):
  File "python_common_mistakes.py", line 4, in <module>
    if fruits[i].startswith('o'):
IndexError: list index out of range

Let’s find out more about this error by printing the value of the index and the size of the list at every iteration of the for loop.

fruits = ['orange', 'apple', 'banana']

for i in range(len(fruits)):
    print("Index: {} - List size: {}".format(i, len(fruits)))
    if fruits[i].startswith('o'):
        fruits.remove(fruits[i])
    print(fruits[i])

[output]
Index: 0 - List size: 3
apple
Index: 1 - List size: 2
banana
Index: 2 - List size: 2
Traceback (most recent call last):
  File "python_common_mistakes.py", line 5, in <module>
    if fruits[i].startswith('o'):
IndexError: list index out of range

We definitely have more info now…

Here is the sequence of events:

  1. First iteration: index is 0, the size of the list is 3, the if condition is True and the string ‘orange’ gets removed from the list fruits. We then print fruits[0] that is now ‘apple’ (because ‘orange’ has been removed from the list).
  2. Second iteration: index is 1, the size of the list is 2, the if condition is False because ‘banana’ doesn’t start with the letter ‘o’. We then print fruits[1] that is ‘banana’.
  3. Third iteration: index is 2 but the size of the list is still 2 so the maximum allowed index is 1. That’s why we see the “list index out of range error”.

The error comes from the fact that the indexes are generated based on the initial size of the list and they don’t change even if the size of the list changes after removing one item from it.

Conclusion

Well done!

Let’s recap the common Python mistakes we have covered in this tutorial:

  1. Incorrect Python indentation causes syntax errors.
  2. The colon cannot be missed at the end of the header in an if statement.
  3. You can’t use a variable before assigning a value to it.
  4. Don’t try to modify an immutable object (e.g. a tuple).
  5. Handle indexes manually in a for loop only when strictly required.
  6. Don’t confuse equality and assignment operators.
  7. Avoid modifying a Python list while looping through it.

And now it’s your turn!

Be aware of these common errors and get coding!

Leave a Reply

Your email address will not be published.

How to Import a Python Function fro... x
How to Import a Python Function from Another File