Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Common Python Coding Mistakes and How to Fix Them

DZone's Guide to

Common Python Coding Mistakes and How to Fix Them

In this post, we go over a few common Python pitfalls and solutions for each in a quest to write more bug-free code. Let's get to it!

· Big Data Zone ·
Free Resource

The Architect’s Guide to Big Data Application Performance. Get the Guide.

Here are some of the common mistakes I run into when solving Python code problems.

I'm trying hard to write more bug-free code (if I can).

Common Mistakes

  • Typo issue: used a wrong variable.
  • Used an improper function name.

ERROR:

if s[left].lower() == s[right].lower:
    left, right = left+1, right-1

OK:

if s[left].lower() == s[right].lower():
    left, right = left+1, right-1
  • Initialize an array by reference:
#!/usr/bin/env python
dp = [{}]*(3)
dp[0] = {0:1}

dp[1][1] = 1
print(dp[2][1]) # which one you will get? 1 or None?

dp[1] == dp[2]
  • Syntax error for Key data structures.
# set/collection
set1.append() # error
set1.add() # ok
# list
l = l.sort() # unexpected
sorted(l) # in-place change or generate a new list?
# array
array1.push() # ok
array1.pop(1) # ok
array1.pop() # error
# string
str[2:4] = 'ab' # error. Can't change string
  • Forget to add the this. decorator for class function members.
#  From:
self.ch = self.string[index]

#  To:
self.ch = self.string[self.index]

#  Errmsg: UnboundLocalError: local variable 'index' referenced before assignment
  • array index: For l[left:right], the right element is not excluded.
  • Corner case: Forgot to process the initial state.
  • Transfer by value vs by reference: Design Twitter

ERROR:

##  Blog link: https://brain.dennyzhang.com/design-twitter
def getNewsFeed(self, userId):
        l = self.tweet_dict[userId]
        for followee in self.follow_dict[userId]:
            l += self.tweet_dict[followee]
        l.sort(reverse=True) 
        return l[0:10]

OK:

##  Blog link: https://brain.dennyzhang.com/design-twitter
def getNewsFeed(self, userId):
        l = copy.deepcopy(self.tweet_dict[userId])
        for followee in self.follow_dict[userId]:
            l += self.tweet_dict[followee]
        l.sort(reverse=True) 
        return l[0:10]
  • When adding to a set, we will remove duplicates; meanwhile, when adding to a list, we will keep the duplicates.

ERROR:

##  Blog link: https://brain.dennyzhang.com/design-snake-game
if len(self.foods) == 0 or [x2, y2] != self.foods[0]:
    self.snake_points_set.add((x2, y2))
    self.snake_points.append((x2, y2))

    self.snake_points_set.remove(self.snake_points[0])
    self.snake_points.popleft()
    return self.food_index

OK:

if len(self.foods) == 0 or [x2, y2] != self.foods[0]:
    first_point = self.snake_points.popleft()
    self.snake_points.append((x2, y2))

    self.snake_points_set.add((x2, y2))
    self.snake_points_set.remove(first_point)
    return self.food_index

Learn how taking a DataOps approach will help you speed up processes and increase data quality by providing streamlined analytics pipelines via automation and testing. Learn More.

Topics:
python ,bug fixing ,clean code ,big data

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}