← Back to Blog
    TutorialJanuary 25, 202410 min read

    10 Common Python Mistakes and How to Fix Them

    Learn the most common Python mistakes beginners make and how to avoid them. Improve your coding skills with practical examples.

    10 Common Python Mistakes and How to Fix Them

    1. Mutable Default Arguments

    Wrong:

    ```python

    def append_item(item, lst=[]):

    lst.append(item)

    return lst

    print(append_item(1)) # [1]

    print(append_item(2)) # [1, 2] - Oops!

    ```

    Right:

    ```python

    def append_item(item, lst=None):

    if lst is None:

    lst = []

    lst.append(item)

    return lst

    ```

    2. Forgetting Colons in Control Structures

    Wrong:

    ```python

    if x > 5

    print("x is large")

    ```

    Right:

    ```python

    if x > 5:

    print("x is large")

    ```

    3. Confusion Between = and ==

    Wrong:

    ```python

    if x = 5: # SyntaxError

    print(x)

    ```

    Right:

    ```python

    if x == 5:

    print(x)

    ```

    4. Off-by-One Errors with range()

    Wrong:

    ```python

    for i in range(1, 5): # Goes 1, 2, 3, 4 (not 5)

    print(i)

    ```

    5. Modifying Lists While Iterating

    Wrong:

    ```python

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

    for num in nums:

    if num % 2 == 0:

    nums.remove(num) # Skips elements!

    ```

    Right:

    ```python

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

    nums = [n for n in nums if n % 2 != 0]

    ```

    6. Confusing None with False

    Wrong:

    ```python

    if not value: # Treats None, False, 0, "" the same

    print("empty")

    ```

    Right:

    ```python

    if value is None:

    print("value is None")

    ```

    7. Shadowing Built-ins

    Wrong:

    ```python

    list = [1, 2, 3] # Now list() function is gone!

    new_list = list() # TypeError

    ```

    Right:

    ```python

    my_list = [1, 2, 3]

    ```

    8. Index Out of Range

    Wrong:

    ```python

    lst = [1, 2, 3]

    print(lst[5]) # IndexError

    ```

    Right:

    ```python

    lst = [1, 2, 3]

    if len(lst) > 5:

    print(lst[5])

    Or use get() for dicts

    ```

    9. Forgetting Global Keyword

    Wrong:

    ```python

    x = 10

    def change_x():

    x = 20 # Creates local variable, doesn''t change global

    change_x()

    print(x) # 10

    ```

    Right:

    ```python

    x = 10

    def change_x():

    global x

    x = 20

    change_x()

    print(x) # 20

    ```

    10. String Concatenation in Loops

    Wrong:

    ```python

    result = ""

    for i in range(1000):

    result += str(i) # Slow! Creates new string each time

    ```

    Right:

    ```python

    result = "".join(str(i) for i in range(1000))

    ```

    Summary

    Avoid these mistakes by:

    • Using linters (pylint, flake8)
    • Writing tests
    • Code reviews
    • Practice on PythonExecutor!

    By PythonExecutor Team

    Related Articles