Skip to content

Commit e24dd4f

Browse files
committed
Create not_using_unpacking_for_updating_multiple_values_at_once.rst.
1 parent 92a8f22 commit e24dd4f

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
Not using unpacking for updating multiple values at once
2+
========================================================
3+
4+
Summary
5+
-------
6+
7+
For simple updates to multiple variables, use unpacking to update the values rather than using assignments to update each value individually.
8+
9+
Description
10+
-----------
11+
12+
In general, the Python programming community prefers concise code over verbose code. Using unpacking to update the values of multiple variables simultaneously is more concise than using assignments to update each variable individually.
13+
14+
Examples
15+
----------
16+
17+
Using assignments to individually update the values of variables
18+
................................................................
19+
20+
The module below updates the values of the two variables ``x`` and ``y`` using assignments that are on separate lines of code.
21+
22+
.. warning:: The code below is an example of an error. Using this code will create bugs in your programs!
23+
24+
.. code:: python
25+
26+
x = 1
27+
y = 2
28+
z = 0
29+
30+
# The method below is not the preferred way to update multiple values
31+
x = y + 2 # 4
32+
y = x - 3 # 1
33+
z = x + y # 5
34+
35+
Solutions
36+
---------
37+
38+
Use unpacking to update multiple values simultaneously
39+
......................................................
40+
41+
The modified module below is functionally equivalent to the original module above, but this module is more concise.
42+
43+
.. code:: python
44+
45+
x = 1
46+
y = 2
47+
z = 0
48+
49+
x, y, z = y + 2, x - 3, x + y # more concise
50+
51+
References
52+
----------

0 commit comments

Comments
 (0)