From ba238cfa8279a7253bb4ef020baad7408417faa4 Mon Sep 17 00:00:00 2001 From: Satwik Kansal Date: Fri, 1 Sep 2017 14:50:13 +0530 Subject: [PATCH] Add example: Loop variable resilient to changes Closes https://github.com/satwikkansal/wtfPython/issues/11 --- README.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/README.md b/README.md index 7a5a54c..766a5db 100755 --- a/README.md +++ b/README.md @@ -1407,6 +1407,36 @@ tuple() --- +### Loop variable resilient to changes + +Suggested by @tukkek in [this](https://github.com/satwikkansal/wtfPython/issues/11) issue. + +```py +for i in range(7): + print(i) + i = 10 +``` + +**Output:** +``` +0 +1 +2 +3 +4 +5 +6 +``` + +Did you expect the loop to run just once? + +#### 💡 Explanation: + +- [Source](https://docs.python.org/3/reference/compound_stmts.html#the-for-statement) +- The assignment statement `i = 10` never affects the iterations of the loop because of the way for loops work in Python. Before the beginning of every iteration, the next item provided by the iterator (`range(7)` this case) is unpacked and assigned the target list variables (`i` in this case). + +--- + ### Let's see if you can guess this? Suggested by @PiaFraus in [this](https://github.com/satwikkansal/wtfPython/issues/9) issue.