Skip to content

Commit 8ae68f1

Browse files
committed
Add new example
Closes satwikkansal#9
1 parent f76511c commit 8ae68f1

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

README.md

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1396,6 +1396,59 @@ tuple()
13961396

13971397
---
13981398

1399+
### Let's see if you can guess this?
1400+
1401+
Originally, suggested by @PiaFraus in [this](https://github.com/satwikkansal/wtfPython/issues/9) issue.
1402+
1403+
**Output:**
1404+
```py
1405+
>>> a, b = a[b] = {}, 5
1406+
>>> a
1407+
{5: ({...}, 5)}
1408+
```
1409+
1410+
#### 💡 Explanation:
1411+
1412+
* According to [Python language reference](https://docs.python.org/2/reference/simple_stmts.html#assignment-statements), assignment statements have the form
1413+
```
1414+
(target_list "=")+ (expression_list | yield_expression)
1415+
```
1416+
and
1417+
> An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.
1418+
1419+
* The `+` in `(target_list "=")+` means there can be **one or more** target lists. In this case, target lists are `a, b` and `a[b]` (note the expression list is exactly one, which in our case is `{}, 5`).
1420+
1421+
* After the expression list is evaluated, it's value is unpacked to the target lists from **left to right**. So, in our case, first the `{}, 5` tuple is unpacked to `a, b` and we now have `a = {}` and `b = 5`.
1422+
1423+
* `a` is now assigned to `{}` which is a mutable object.
1424+
1425+
* The second target list is `a[b]` (you may expect this to throw an error because both `a` and `b` have not been defined in the statements before. But remember, we just assigned `a` to `{}` and `b` to `5`).
1426+
1427+
* Now, we are setting the key `5` in the dictionary to the tuple `({}, 5)` creating a circular reference (the `{...}` in the output refers to the same object that `a` is already referencing). Another simpler example of circular reference could be
1428+
```py
1429+
>>> some_list = some_list[0] = [0]
1430+
>>> some_list
1431+
[[...]]
1432+
>>> some_list[0]
1433+
[[...]]
1434+
>>> some_list is some_list[0]
1435+
[[...]]
1436+
```
1437+
Similar is the case in our example (`a[b][0]` is the same object as `a`)
1438+
1439+
* So to sum it up, you can break the example down to
1440+
```py
1441+
a, b = {}, 5
1442+
a[b] = a, b
1443+
```
1444+
And the circular reference can be justified by the fact that `a[b][0]` is the same object as `a`
1445+
```py
1446+
>>> a[b][0] is a
1447+
True
1448+
```
1449+
1450+
---
1451+
13991452
### Minor Ones
14001453

14011454
* `join()` is a string operation instead of list operation. (sort of counter-intuitive at first usage)

0 commit comments

Comments
 (0)