Most Frequently Used Python Code Fragments

Python syntax may seem strange at the beginning for Java developers. Wouldn't it be nice if we first see how Python does the common jobs that we have done using other programming languages, like Java? The common code fragments are call "code idioms". Reading the code idioms of a programming language is often helpful, and can be served as a shortcut for learning a new programming language.

The intent of this post is to list some of the most commonly used Python code idioms, in the hope that it will provide useful recommendations for other programmers (especially beginners). Remember that in addition to the listings below, there are other frequently used Python code fragments. You may also want to check you the most popular 3000 python modules.

*Note: The order does not reflect each code idiom's frequency.

# Filter a list

#filter out empty strings in a sting list
list = [x for x in list if x.strip()!='']

# Read file line by line

with open("/path/to/file") as f:
    for line in f:
        print line

# Write file line by line

f = open("/path/tofile", 'w')
for e in aList:
    f.write(e + "\n")

# Regular expression finding

sentence = "this is a test, not testing."
it = re.finditer('\\btest\\b', sentence)
for match in it:
    print "match position: " + str(match.start()) +"-"+ str(match.end())

# Regular expression search

m ='\d+-\d+', line) #search 123-123 like strings
if m:
    current =

# Query database

db = MySQLdb.connect("localhost","username","password","dbname")
cursor = db.cursor()
sql = "select Column1,Column2 from Table1"
results = cursor.fetchall()
for row in results:
    print row[0]+row[1]

# Connet a list with a specified separator

theList = ["a","b","c"]
joinedString = ",".join(theList)

# Filter out duplicate elements

targetList = list(set(targetList))

# Filter out empty strings from a list of strings

targetList = [v for v in targetList if not v.strip()=='']
# or
targetList = filter(lambda x: len(x)>0, targetList)

# Add a list to another list


# Iterate a dictionary

for k,v in aDict.iteritems():
    print k+v

# Check if any element of a string list appears in a target string

if any(x in targetString for x in aList):
    print "true"

Apparently, not all Python code idioms are shown above. I would appreciate if you can add more in your comment.

If you are a Java programmer, and you are totally new to Python, I recommend you read the the following:

Category >> Python  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";
  • Paddy3118

    When defining regular expression string literals in Python it is more elegant to use “raw strings” where the string literal is prefixed by an ‘r’ and backslashes loose any special processing within the string so you should write in the regular expression example: ...'d+-d+', ...

  • Paddy3118

    You can use a with statement for the writing too and get an implicit file close:

    # Write file line by line
    with open("/path/to/file", 'w') as f:
    for e in aList:
    f.write(e + "n")

  • Paddy3118

    It is more pythonic to test an object directly, as empty objects such as empty strings are False leading to:

    #filter out empty strings in a sting list
    non_empties = [mystring for mystring in input_list if mystring.strip()]

  • felipealexander

    It’s just nice to see the good and neat explanation for each codes. My humble request is i just needed the explanation about the evolution of python programming as i have been working as a research paper writer in buy research paper online website, i have been requested by a client to do the research paper about the evolution and development of python, i am requesting you all to guide me to complete my research paper in a best way.