Click here to Skip to main content
15,892,059 members
Articles / Programming Languages / Python2.7
Tip/Trick

Python Code Optimizations: Part 2

Rate me:
Please Sign up or sign in to vote.
4.71/5 (6 votes)
2 Nov 2014CPOL1 min read 18K   8   5
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)


Written By
Software Developer (Senior) Mindfire Solutions
India India
Writing python code @ Mindfire Solutions, Noida.

Comments and Discussions

 
QuestionDistinguishing Multiple Exit Points in a Loop Pin
Reverend Jim21-Sep-21 9:10
Reverend Jim21-Sep-21 9:10 
BugVariable name mismatch Pin
Chad3F8-Nov-14 20:54
Chad3F8-Nov-14 20:54 
GeneralRe: Variable name mismatch Pin
Dhruv Singh10-Nov-14 3:21
professionalDhruv Singh10-Nov-14 3:21 
SuggestionJust some polish Pin
Moranoa4-Nov-14 10:27
Moranoa4-Nov-14 10:27 
GeneralRe: Just some polish Pin
Dhruv Singh5-Nov-14 5:42
professionalDhruv Singh5-Nov-14 5:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.