mirror of
https://github.com/kennethreitz/python-guide.git
synced 2026-06-05 14:50:19 +00:00
some idioms I used this morning
This commit is contained in:
+53
-2
@@ -3,9 +3,60 @@ Code Style
|
||||
|
||||
|
||||
Idioms
|
||||
::::::
|
||||
------
|
||||
|
||||
Idiomatic Python code is often referred to as being *Pythonic*.
|
||||
|
||||
.. _unpacking-ref:
|
||||
|
||||
Unpacking
|
||||
~~~~~~~~~
|
||||
|
||||
If you know the length of a list or tuple, you can assign names to its
|
||||
elements with unpacking:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
for index, item in enumerate(some_list):
|
||||
# do something with index and item
|
||||
|
||||
You can use this to swap variables, as well:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
a, b = b, a
|
||||
|
||||
Create an ignored variable
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
If you need to assign something (for instance, in :ref:`unpacking-ref`) but
|
||||
will not need that variable, use ``_``:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
filename = 'foobar.txt'
|
||||
basename, _, ext = filename.rpartition()
|
||||
|
||||
Create a length-N list of the same thing
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Use the Python list ``*`` operator:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
four_nones = [None] * 4
|
||||
|
||||
Create a length-N list of lists
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Because lists are mutable, the ``*`` operator (as above) will create a list
|
||||
of N references to the `same` list, which is not likely what you want.
|
||||
Instead, use a list comprehension:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
four_lists = [[] for _ in xrange(4)]
|
||||
|
||||
Idiomatic Python code is often referred to as being *pythonic*.
|
||||
|
||||
|
||||
Zen of Python
|
||||
|
||||
Reference in New Issue
Block a user