@@ -3,9 +3,60 @@ 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+ Create a length-N list of the same thing
41+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
42+
43+ Use the Python list ``* `` operator:
44+
45+ .. code-block :: python
46+
47+ four_nones = [None ] * 4
48+
49+ Create a length-N list of lists
50+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
51+
52+ Because lists are mutable, the ``* `` operator (as above) will create a list
53+ of N references to the `same ` list, which is not likely what you want.
54+ Instead, use a list comprehension:
55+
56+ .. code-block :: python
57+
58+ four_lists = [[] for _ in xrange (4 )]
759
8- Idiomatic Python code is often referred to as being *pythonic *.
960
1061
1162 Zen of Python
0 commit comments