@@ -3,9 +3,67 @@ Code Style
33
44
55Idioms
6- ::::::
6+ ------
7+
8+ Idiomatic Python code is often referred to as being *Pythonic *.
9+
10+ .. _unpacking-ref :
11+
12+ Unpacking
13+ ~~~~~~~~~
14+
15+ If you know the length of a list or tuple, you can assign names to its
16+ elements with unpacking:
17+
18+ .. code-block :: python
19+
20+ for index, item in enumerate (some_list):
21+ # do something with index and item
22+
23+ You can use this to swap variables, as well:
24+
25+ .. code-block :: python
26+
27+ a, b = b, a
28+
29+ Create an ignored variable
30+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
31+
32+ If you need to assign something (for instance, in :ref: `unpacking-ref `) but
33+ will not need that variable, use ``_ ``:
34+
35+ .. code-block :: python
36+
37+ filename = ' foobar.txt'
38+ basename, _, ext = filename.rpartition()
39+
40+ .. note ::
41+
42+ "``_ ``" is commonly used as an alias for the :func: `~gettext.gettext `
43+ function. If your application uses (or may someday use) :mod: `gettext `,
44+ you may want to avoid using ``_ `` for ignored variables, as you may
45+ accidentally shadow :func: `~gettext.gettext `.
46+
47+ Create a length-N list of the same thing
48+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
49+
50+ Use the Python list ``* `` operator:
51+
52+ .. code-block :: python
53+
54+ four_nones = [None ] * 4
55+
56+ Create a length-N list of lists
57+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
58+
59+ Because lists are mutable, the ``* `` operator (as above) will create a list
60+ of N references to the `same ` list, which is not likely what you want.
61+ Instead, use a list comprehension:
62+
63+ .. code-block :: python
64+
65+ four_lists = [[] for _ in xrange (4 )]
766
8- Idiomatic Python code is often referred to as being *pythonic *.
967
1068
1169 Zen of Python
0 commit comments