Find First Pattern in Python

When coding in Python, I often see this pattern:

filename = [f for f in file_list if ....][0]

The above expression traverses through the whole list to find items that fit the criteria (the if phrase), then return the first item.

This construction is inefficient because it did not stop even after it found the first item. The effect is more obvious if one or more of these conditions happen:

  • The list is long
  • The criteria is time consuming
  • This construction happens several times

A better, more efficient approach is to stop searching once you found your candidate:

filename = next(f for f in file_list if ...)

In this approach, the expression inside the next function is a generator expression which returns a generator object. The next function returns the first item that fits the criteria. The net effect is the code does not traverse the entire list. Instead, it stops right after locating the first item.

Note that both approaches do not guard against such cases as empty list for file_list, or when the search came up empty.

Likewise, to find the last item, instead of:

filename = [f for f in file_list if ....][-1]

Do this:

filename = next(f for f in reversed(file_list) if ...)

The reversed function requires its argument to be a sequence (list, tuple, …) and reverse itself returns a generator object. In this situation, we have nested generators, but the effect is the same: the code will stop once it found the last item that fits the criteria and not traversing the entire list.


Eliminate If from Your Code


We often write code with too many if statements. If statements are fine, but in many cases, we can eliminate them, making the code simpler and faster.

Example 1: The "or" Trick

In this example, we create a linked list data structure:

class List(object):
    def __init__(self, iterable=None):
        self.head = None
        self.tail = None
        self.length = 0
        if iterable:
            for item in iterable:

In this example, the linked list's __init__ method takes in an optional iterable object (an object that we can iterate through). If the iterable is not None, we then iterate through it and append them one by one. At the first glance, the if statement does have its place: it prevents the for loop from iterating over a None object, which causes runtime error.

The key to remove the if statement lies in the fact that we cannot iterate through the None object, but an empty list:

class List(object):
    def __init__(self, iterable=None):
        self.head = None
        self.tail = None
        self.length = 0
        for item in iterable or []:

The expression iterable or [] will return the iterable if it is "true", or an empty list if not. When iterable is None, we will iterate through an empty list, which means the body of the for loop will execute zero times.

Example 2: Toggle Values

Consider the following pattern:

if flag:
    flag = False
    flag = True

This block of code toggles the value of flag between True and False. A simpler and more efficient way is:

flag = not flag

Example 3: Boolean Equality Test

Believe it or not, I see the following a few times in my career:

if expected == True and actual == True:
    return True
elif expected == False and actual == False:
    return True
else return False


if (expected == True and actual == True) or \
   (expected == False and actual == False):
    return True
else return False

The two blocks above say:

If the values of actual and expected are both True or are both False then we return True, otherwise we return False.

In other word, these blocks test to see if actual is the same as expected:

return actual == expected

Example 4: Nested If

I also frequently see code like this:

if wrap_around:
    if x == MAX_WIDTH:
        x = 0
        y += 1

Depend on the situation, we might not be able to eliminate the if statements altogether, but we can reduce the nesting:

if wrap_around and x == MAX_WIDTH:
    x = 0
    y += 1

Example 5: Cycle of Values

In the following example, the coder wanted value of column to cycle between 0 and 7:

column = 0
for cell in data:
    # do something
    column += 1
    if column == 8:
        column = 0

The quick and easy way to improve this code is to employ the modulus operator:

column = 0
for cell in data:
    # do something
    column = (column + 1) % 8

Another fix is to use the cycle function:

from itertools import izip, cycle

for column, cell in izip(cycle(range(8)), data):
    # Do something

In this case, range(8) returns [0, 1, 2, 3, 4, 5, 6, 7] and range will keep cycling values in that list forever. The izip function then pairs that 0-7 cycle with the data.


These are just a couple of instances where we can eliminate the if statements and make the code shorter, faster, and simpler to understand.

Simple Online IDE for Python

I am in need of a quick way to post Python code snippet online, run it and show output. My research points me to quite a few and I like three of them.



What I like

  • No ad!
  • Does not require signing up to use
  • The code and the output are nicely formatted and easy to view
  • Once submitted, codepad generates a new page with a unique URL. The users cannot change the code unless they choose to fork. This is great to present someone a code snippet without fear of someone modifying it
  • Has a comment section, good for discussion

Improvements Wish List

  • Syntax highlight
  • Code completion
  • Optional title, description, and tags

Python Fiddle


What I like

  • No ad!
  • Does not require signing up to use
  • Syntax highlight
  • Code completion
  • Large editing area

Improvements Wish List

  • Buggy sometimes. I typed import json and got invalid syntax on print import json
  • Importing of modules takes a long time: the first time I import json, it took about 2 seconds
  • Output not clearly labeled



What I like

  • Does not require signing up to use
  • Syntax highlight
  • Many languages
  • Ability to specify stdin

Improvements Wish List

  • Larger editing area
  • Required Flash
  • Lots of ads
  • Output is burried below an ad

Why Returning a Mutable Attribute Might Be Dangerous

Avoid Returning Mutable Attribute

People who come from C++, Java or C# often provide getter/setter to provide access to their classes’ internals. In Python, there is not point to use getter/setter unless there is a good reason for doing so. I have been coding in Python for several years and have not yet come by one such reason.

I have seen code where people prefix a class instance’s attribute with underscore thinking it should make that attribute private. The following example will demonstrate that point:

class Car(object):
    def __init__(self, owners):
        self._owners = owners

    def get_owners(self):
        return self._owners

if __name__ == '__main__':
    car = Car(['Peter', 'Paul'])
    print 'This car belongs to', car.get_owners()

    owners = car.get_owners()
    print 'This car belongs to', car.get_owners()


This car belongs to ['Peter', 'Paul']
This car belongs to ['Peter', 'Paul', 'Mary']

In the example above, the user calls car.getowners() to gain access to a private member, but then went on modifying it. The immediate solution is to return a copy of self.owners. That way, changes made to the copy does not affect the original member.

Avoid Returning Attributes at All

Instead of allowing the users to gain access to your class’ internals, why not provide what the users really want. Think of a class attributes as nouns (things) and methods as verbs (actions). A class should provide the users with actions, not nouns.

Here is a typical example:

import fnmatch

class FileFilter(object):
    def __init__(self, include=None):
        self._include = include

    def include_patterns(self):
        return self._include[:]

# Usage example: prints all the files that fit a set of patterns
filter = FileFilter(include=['*.py', '*.ipynb'])
for filename in ['readme.txt', '', 'greeting.ipynb']:
    for pattern in filter.include_patterns:
        if fnmatch.fnmatch(filename, pattern):
            print filename


Provide Services Instead of Attributes

In the example above, the class FileFilter provides a getter, include which returns a list of pattern. Instead of providing the users with an attribute (self.include, a noun), it should instead provide a service, an action, namely: shouldinclude:

import fnmatch

class FileFilter(object):
    def __init__(self, include=None):
        self._include = include

    def should_include(self, filename):
        return any(fnmatch.fnmatch(filename, pattern) for pattern in self._include)

# Usage example: prints all the files that fit a set of patterns
filter = FileFilter(include=['*.py', '*.ipynb'])
for filename in ['readme.txt', '', 'greeting.ipynb']:
    if filter.should_include(filename):
        print filename


Notice in the example above, FileFilter does not expose any internal data. Instead, it offers a service (an action, or verb, namely should_include). Also notice the code which uses the FileFilter class is also simpler, with one less nested level.


When designing a class, you should avoid returning a class’ internal data, especially mutable structures. Instead, you need to study the users code to see what they use those data for and offer services to accomplish their goals.

Disney Cruise 2013

Day One: Getting on Board

The Disney Fantasy

We boarded the ship as early as we could in order to spend as much time on the ship as possible. Think about it, cruises are not cheap, so the more we spend on the ship, the better bang for the buck we get.

Once aboard, we took the advice from other seasoned travelers and went straight to the lunch room as our stateroom (that’s what they called our room) were not yet ready. Many chose to went swimming before having lunch. We went to our stateroom around 1:30PM to find our luggages ready outside the door.

Dinner was very nice. The portions seem little, but we got very full because of the appetizer, bread, main course, then dessert. If you have food allergy like I do, then let your server know as soon as you pass the introduction. The same server will serve you for the whole duration of the trip, so you don’t have to repeat what you said, which is nice.

After dinner, we went to the theater and got in line early. Seatings in the theater are limited so be there early to get a good seat. The cruise director advised not to save seats for your party, so you need to all be there or risk losing your seats. We highly recommend going to the theaters after dinner and do not miss any show. These are the kind of shows that back home might cost anywhere from $50/ticket to $150, so you might want to maximize your money’s worth.

Day Two: at Sea

We spent the second day exploring the ship. Since we did not bring a lot of clothes, we started searching for self-service laundry room. The one we used had about four washers and four dryer. We purchased detergent and dryer sheets right in the room using our keycard. These are not cheap: while detergent and dryer sheet cost about two dollars each, adding to that the cost of operating washer and dryer, the cost per load is about $10-$12. Budget-conscious travelers might want to bring detergent and dryer sheets from home. We highly recommend of bringing dryer sheets: they add almost no weight to the luggage, but save a lot of money. If you bring them, make sure to keep them inside zip lock bags or they will loose their magic freshness.

Day Three: Grand Cayman

Grand Cayman Beach

We did not buy on-shore packages from Disney. Instead, we just played it Russian-roulette style: We got off the ship and “shop” around for destinations. We ended up in wonderful beach which I forgot the name.

Grand Cayman is part of the British-oversee territory and it showed in the way people drive on the left side of the road. From the beach, we could smell the pungent smell of durian. Except for our younger daughter, we all love durian. However, if you don’t like (read: are terrified of) durian, let your driver know.

We spent most of our time on Grand Cayman at the same beach. Originally, we wanted to explore the town, but our daughters did not want to leave the beach. Being from Seattle, where the water is too cold year-round, we could not blame them.

Day Four: Costa Maya, Mexico

Chacchoben Maya Ruin

We decided to book through Disney for our excursion to see the Chacchoben Maya Ruin–a set of pyramid structures. When we got ashore, we got on one of the buses heading to the site, which took about an hour. Unfortunately, it was raining on that day, but the pyramids were an incredible sight. Since the trip took four to four and a half hours to complete, we disembark as soon as we could.

Since it was raining, the site was muddy and slippery. It was a good thing that we brought with us the raincoats that the cruise staff gave us. The rain prevent us from taking many pictures and video, but we did manage to capture a few shots. For those who care about history or anthropology, this is a must-visit place.

Day Five: Cozumel, Mexico


My daughters wanted to go on the Dolphin Discovery excursion, but instead of booking through Disney, we chose to book it ourselves to see if we saved any money. As soon as we got on shore and walked outside the fenced area, we saw a busy street full of shops and taxis. We asked for direction to “the dolphin place” which many people gave different answers. Finally, we booked through a middleman, who told us the price would include taxi ride to our destination and back.

When we arrived at Chankanaab, dolphin discovery park, we learned a few things. First, the price is identical whether we booked through an agent on the street, or at Chankanaab. However booking at Chankanaab is safer because we did not have to pay the middleman cash deposit. Second, we were swindled as the price did not include any taxi ride back, which costed $12 (prices in US dollars). If we were booking from Disney, the price would be $112 x 2 = $224 with transportation. When we booked ourselves, the price came to $79 x 2 = $158. Add $12 for transportation, we ended up spending $170 for the two kids–a $54 saving for two kids, or $27 per person. Also, in order to get into the park area to watch our kids, both my wife and I had to pay entrance fee of $21/person, which would be $26 if booked through the middleman. Fortunately, we did not. So, the lessons I learned from this excursion are:

  • Learn the name of your destination to make it easer on your transport
  • Take a taxi ride (or other mode of transportation) there. Do not book through any agent or middleman.
  • If you want peace of mind, book through Disney. It might worth $27/person premium.

Once we arrived at the park, we had an hour before the next dolphin session. At this point, our family can get into a large pool, a mini lagoon, or hang around the bars, shops within the park. My wife and I chose stay dry while the kids had a good time around the pool. They preferred this pool over the one on the ship since it was larger, and much less crowded.

The park did not allow parents to accompany the kids in order to take pictures, unless we paid yet another fee. We chose not to do that and enjoyed ourselves at the Cove–their restaurant. The Guacamole and chips was good and the price was right: about $5.75 (US dollar).

Our kids had a great time with the dolphins, we could see it in the pictures the park took. However, they demanded $37 per picture, or all 24 of them for $124. Again, we chose not to purchase due to the high price.

Day Six: at Sea

Inside the Fantasy

On this day, we continued to explore the ship. We spent our morning at the pools and hot tubs. We also visited the movie theater and saw The Lone Ranger. We also took this opportunity of taking many photos at various places, especially with the Disney characters. At night, after the nightly show, we went to a club and found that they played disco of the 70’s. What a night!

Day Seven: Castaway Cay

Castaway Cay

We decided to go on shore as early as we could and it paid off: when we got the the beach, it is already full of people and we were lucky to find some chairs. Castaway Cay (pronounce: key) has to beaches. If you don’t find any chairs from the first one, continue on to the second one.

Next to our beach, Disney has a private beach for those who pay or belong to some sort of clubs. We recommend to to pay, unless you like to have an empty beach to yourself. We did not find may people there, only a handful.


  • Check in at least three days in advance so you can choose the time that is convenient. Disney said the check-in time is from 1:00PM to 3:30PM, but we arrived early and was able to get in around 12:30PM.
  • Once on board, you can immediately hit the pools on deck 11 since they are not crowded.
  • Another option is to have lunch, also on deck 11. For the kids, they offer the “kid-comfort” food by the pool: pizza, burger, sandwiches… For the adults and kids alike, head the rear (aft) of deck 11 for the Cabana, a buffet-style lunch-and-breakfast place.
  • Don’t waste for first hours checking out the ship–you can perform your inspection later. Instead, go swimming or have lunch.
  • If you get seasick, head to the guest services on deck three midship and ask for some pills.
  • Buy bottled water and bring them onboard. I saw many families who bought them by 24-bottle cases and the cruise will bring them to their staterooms. While drink is free on the ship, there is no water in the staterooms, unless you take a long walk to the dining rooms and get them. You can also buy bottled water onboard, but it is expensive.

Post-It Notes Resume


I am currently searching for a job, as the result, I often carry in my “murse” (man-purse) a stack of paper resume. Due to the size of the bag (a Tom Bihn Small Cafe bag), I have to fold the pages in half. In addition, these pages add bulk in a bag where space is already at a premium.


To solve this problem, I put my resume online, then point people to it.

Posting Resume Online

I used Google Docs to create my resume. Consequently, they already available online. All I need to do is to make my document public and received a random (and long) URL. The next step is to shorten that URL using a URL-shortening service such as Now that I have a short, easy-to-type URL, the next step is how to give that URL to someone. Writing on a piece of paper is always an option, but there is a better way.

Post-It Note Resume

To easily hand out my resume, I print the URL for my resume, along with a QR code on Post-It notes and carry those notes with me. These notes take only a fraction of spaces compare to the full letter-size pages of my resume. They are easier to hand out as well.

To create the QR code, I searched online and found many places to do so. I used for my creation, but other sites work as well. Next, I searched online for a way to print onto Post-It notes and found many pointers as well. The one I used was from a site called One Good Thing.

How to type Vietnamese on Windows 7

Typing Vietnamese on Windows 7 does not require any third-party software. All we need is to enable the Vietnamese keyboard and learn how to type special characters.



Open Control Panel and click on Clock, Language and Region.


Click on Change keyboards or other input methods at the bottom of the right pane.


Click Change keyboards…


In the Text Services and Input Languages window, click Add…


Select Vietnamese from the list and click OK.


We will see the Vietnamese keyboard added. Click  OK and we are done with the installation.


How to Type Vietnamese Text

The first step is to switch the keyboard from English (or your current language) to Vietnamese.  Look at the bottom of right of the screen, we will see “EN” for English. Click on it and select “VI” for Vietnamese.



Next, we will learn how to type special Vietnamese characters:

Huyền = 5
Hỏi = 6
Ngã = 7
Sắc = 8
Nặng = 9

ă = 1
â = 2
ê = 3
ô = 4
đ = 0
ư = [
ơ = ]

Good luck.