Behavior of the for-else construct
Avi Gross
avigross at verizon.net
Fri Mar 4 11:43:09 EST 2022
Dieter,
Your use is creative albeit it is not "needed" since all it does is make sure your variable is initialized to something, specifically None.
So would this not do the same thing?
eye = None
for eye in range(0):
print(eye)
eye
If I understand it, your example depends on a variable that is not yet initialized to be used in a loop and retain the last value after the loop. You then set it to None if it is not used as the loop is skipped. Others have shown an example similar to the above of using a sentinel that lets you know if the loop is skipped.
Of course, there are some advantages in making it clear by doing it you way that the loop (for example if copied and used elsewhere) needs to include the else statement as an integral part.
I would like to suggest a slight modification to the above as in if you are searching for something in either seq1 and if not found in seq2. Call it looking for your green shirt in the closet and if not found, looking in the attic. Would this code make sense as such a use in several ways? In English, look here first and if there is NOTHING there, look in the second place?
closet = []
attic = ["Costumes", "Sheets", "Shirts" ]
for item in closet:
print(item)
if item == "Shirts" : print("FOUND in closet!!")
else:
for item in attic:
print(item)
if item == "Shirts" : print("FOUND in attic!!")
Yes, as discussed, you could do an IF statement to check if closet is empty but for iterators, it gets ...
-----Original Message-----
From: Dieter Maurer <dieter at handshake.de>
To: Rob Cliffe <rob.cliffe at btinternet.com>
Cc: python-list at python.org
Sent: Fri, Mar 4, 2022 2:12 am
Subject: Re: Behavior of the for-else construct
Rob Cliffe wrote at 2022-3-4 00:13 +0000:
>I find it so hard to remember what `for ... else` means that on the very
>few occasions I have used it, I ALWAYS put a comment alongside/below the
>`else` to remind myself (and anyone else unfortunate enough to read my
>code) what triggers it, e.g.
>
> for item in search_list:
> ...
> ... break
> else: # if no item in search_list matched the criteria
>
>You get the idea.
>If I really want to remember what this construct means, I remind myself
>that `else` here really means `no break`. Would have been better if it
>had been spelt `nobreak` or similar in the first place.
One of my use cases for `for - else` does not involve a `break`:
the initialization of the loop variable when the sequence is empty.
It is demonstrated by the following transscript:
```pycon
>>> for i in range(0):
... pass
...
>>> i
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'i' is not defined
>>> for i in range(0):
... pass
... else: i = None
...
>>> i
>>>
```
For this use case, `else` is perfectly named.
--
https://mail.python.org/mailman/listinfo/python-list
More information about the Python-list
mailing list