Skip to content

Commit 70fe617

Browse files
sohaibfarooqisatwikkansal
authored andcommitted
Generator with Slice assignment trick
1 parent 240e216 commit 70fe617

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

README.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ So, here we go...
3333
- [▶ Deep down, we're all the same. *](#-deep-down-were-all-the-same-)
3434
- [▶ For what?](#-for-what)
3535
- [▶ Evaluation time discrepancy](#-evaluation-time-discrepancy)
36+
- [▶ Generator with Slice Assignment](#-generator-with-slice-assignment)
3637
- [`is` is not what it is!](#-is-is-not-what-it-is)
3738
- [▶ A tic-tac-toe where X wins in the first attempt!](#-a-tic-tac-toe-where-x-wins-in-the-first-attempt)
3839
- [▶ The sticky output function](#-the-sticky-output-function)
@@ -385,6 +386,37 @@ array = [2, 8, 22]
385386
386387
---
387388
389+
### ▶ Generator with Slice Assignment
390+
391+
```py
392+
iter1 = [1,2,3,4]
393+
g1 = (x for x in iter1)
394+
iter1 = [1,2,3,4,5]
395+
396+
iter2 = [1,2,3,4]
397+
g2 = (x for x in iter2)
398+
iter2[:] = [1,2,3,4,5]
399+
```
400+
401+
**Output:**
402+
```py
403+
>>>print(list(g1))
404+
[1,2,3,4]
405+
406+
>>> print(list(g2))
407+
[1,2,3,4,5]
408+
```
409+
410+
#### 💡 Explanation
411+
412+
- In the first expression `g1` yields the elements of original list `iter1`(instead of updated one). Since the `in`
413+
clause is evaluated at the time of generator declaration, hence generator expression `g1` still have reference of original list
414+
`iter1`
415+
416+
- In the second example, list `iter1` is updated using slice assignment. Slice assignment, in contrast to normal assignment(which creates a new list), updates the same list. We can view this as the slice of list being replace by the iterable on right hand side of equality. Hence, the generator `g2` yields updated `iter2` elements.
417+
418+
---
419+
388420
### ▶ `is` is not what it is!
389421
390422
The following is a very famous example present all over the internet.

0 commit comments

Comments
 (0)