Computational Thinking + Doing

Non-Pythonic vs. Pythonic Code

Coding in Python that is low latency (minimum completion time) and low overhead (minimum resource consumption).

Want to write efficient Python code? Let’s start with this Easter egg—a list of principles to follow:

import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Python 3 Standard Library

In order to write Pythonic code, we’ll take advantage of:

  • Built-in types: list, tuple, set, dict, and others
  • Built-in functions: print(), len(), range(), round(), enumerate(), map(), zip(), and others
  • Built-in modules: os, sys, itertools, collections, math, and others

Example: Creating a List of Sequenced Numbers

Suppose we wanted to create a list of characters used in a decimal number system (0 to 9). How might we do this?

Good

decimal_chars_good = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(decimal_chars_good)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Better

decimal_chars_better = list(range(0, 10))
print(decimal_chars_better)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Best

decimal_chars_best = list(range(10))
print(decimal_chars_best)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

If we want this list to be a tuple (an immutable list, which would be more appropriate), how might we do this?

decimal_chars_best_tuple = tuple(decimal_chars_best)
type(decimal_chars_best_tuple)
<class 'tuple'>
print(decimal_chars_best_tuple)
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

Example: Creating a New List From a Tuple

The U.S. News & World Report published their 10 Best U.S. National Parks. Here they on this parks tuple from #1 to #10:

# Tuples are created explicitly with parenthesis, while lists are created with brackets
parks = (
    "Yosemite",
    "Yellowstone",
    "Glacier National Park",
    "Grand Canyon",
    "Zion National Park",
    "Grand Teton National Park",
    "Bryce Canyon National Park",
    "Arches National Park",
    "Rocky Mountain National Park",
    "Haleakala National Park"
)

Suppose we want to create a new list (which is different from tuples because tuples are immutable) based on the parks tuple that have twelve characters or less on the park’s name. How might we do this?

Good

i = 0
parks_12_good = []
while i < len(parks):
    if len(parks[i]) <= 12:
        parks_12_good.append(parks[i])
    i += 1
print(parks_12_good)
['Yosemite', 'Yellowstone', 'Grand Canyon']

Better

parks_12_better = []
for park in parks:
    if len(park) <= 12:
        parks_12_better.append(park)
print(parks_12_better)
['Yosemite', 'Yellowstone', 'Grand Canyon']

Best

parks_12_best = [park for park in parks if len(park) <= 12]
print(parks_12_best)
['Yosemite', 'Yellowstone', 'Grand Canyon']
Applied Computing