Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 8311ad2

Browse filesBrowse files
author
Kenneth Reitz
committed
Merge pull request realpython#52 from epequeno/master
Added idioms to style.rst
2 parents 76261ff + d3dbd65 commit 8311ad2
Copy full SHA for 8311ad2

File tree

Expand file treeCollapse file tree

1 file changed

+23
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+23
-0
lines changed

‎docs/writing/style.rst

Copy file name to clipboardExpand all lines: docs/writing/style.rst
+23Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,29 @@ Instead, use a list comprehension:
192192
four_lists = [[] for _ in xrange(4)]
193193
194194
195+
A common idiom for creating strings is to use `join <http://docs.python.org/library/string.html#string.join>`_ on an empty string.::
196+
197+
letters = ['s', 'p', 'a', 'm']
198+
word = ''.join(letters)
199+
200+
This will set the value of the variable *word* to 'spam'. This idiom can be applied to lists and tuples.
201+
202+
Sometimes we need to search through a collection of things. Let's look at two options: lists and dictionaries.
203+
204+
Take the following code for example::
205+
206+
d = {'s': [], 'p': [], 'a': [], 'm': []}
207+
l = ['s', 'p', 'a', 'm']
208+
209+
def lookup_dict(d):
210+
return 's' in d
211+
212+
def lookup_list(l):
213+
return 's' in l
214+
215+
Even though both functions look identical, because *lookup_dict* is utilizing the fact that dictionaries in python are hashtables, the lookup performance between the two is very different.
216+
Python will have to go through each item in the list to find a matching case, which is time consuming. By analysing the hash of the dictionary finding keys in the dict can be done very quickly.
217+
For more information see this `StackOverflow <http://stackoverflow.com/questions/513882/python-list-vs-dict-for-look-up-table>`_ page.
195218
196219
Zen of Python
197220
-------------

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.