DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. Languages
  4. Common Python Coding Mistakes and How to Fix Them

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!

Denny Zhang user avatar by
Denny Zhang
·
Jun. 28, 18 · Code Snippet
Like (3)
Save
Tweet
Share
8.93K Views

Join the DZone community and get the full member experience.

Join For Free

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
Python (language) Coding (social sciences)

Published at DZone with permission of Denny Zhang, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • What To Know Before Implementing IIoT
  • Shift-Left: A Developer's Pipe(line) Dream?
  • Building the Next-Generation Data Lakehouse: 10X Performance
  • Best Navicat Alternative for Windows

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: