Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Python2.7

Python Code Optimizations: Part 2

4.71/5 (6 votes)
2 Nov 2014CPOL1 min read 18.5K  
Follow the tips below to write more beautiful and idiomatic Python code!

Introduction

Part 1 of this series can be viewed at this link.

Using the Code

1. Call a Function Until a Sentinel Value

blocks = []
while True:
    block = f.read(32)
    if block == '':
        break
    blocks.append(block)

Pythonic Way: use iter()

blocks = []
for block in iter(partial(f.read, 32), ''):
    blocks.append(block)

iter() can take 2 arguments where the first argument is the function that you call over and over again and the second argument is the sentinel value.
In order to make it work, the first function in iter() needs to be a function with no argument.
But we know f.read() takes one argument in the call, so in order to make it work, we use partial(), which reduces a function of many arguments to a function of fewer/lesser arguments.

2. Distinguishing Multiple Exit Points in a Loop

def find(seq, target):
    found = False
    for i, value in enumerate(seq):
        if value == target:
            found = True
            return i
    if not found:
        return -1

Pythonic Way: Use else in for loop

def find(seq, target):
    for i, value in enumerate(seq):
        if value == target:
            return i
    else:
        return -1

In the above example, the loop works in two parts as:

  1. If we finished the loop and didn't encounter a break, return -1 else
  2. If we finished the loop normally, return i.

Below, I've given a small anecdote which might help you to understand it better!

Consider a small example that many of us face everyday!
Searching your house for keys, it has the following two outcomes:

  1. You find the keys and come out with the keys. or, (return i)
  2. You search all the rooms and there are no more to search for & thus you come out empty handed. (return -1).

3. Looping Over Dictionary Keys

Pythonic Way

d = {'a' : 'apple', 'b' : 'ball', 'c' : 'cat'}
for k in d:
    print k
Quote:

If you treat list as a dictionary, the indices of a list are parallel to the keys in a dictionary.

4. Mutating a Dictionary

Pythonic Way

for k in d.keys():
    if k.startswith('a'):
        del d[k]
Quote:

If you want to mutate a dictionary, you can't do it when you are iterating over it.

In this case, <a href="https://docs.python.org/2/tutorial/datastructures.html#dictionaries">d.keys()</a> calls the keys argument and makes a copy of all the keys and stores it in a list.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)