15 ms·
Python’s For - Else
- kbumsik 8y agoIt is worth noting that the else clause can also be used with while loops. [1]: https://docs.python.org/3.6/reference/compound_stmts.html#while https://docs.python.org/3.6/reference/compound_stmts.html#wh...
- kasbah 8y agoSeems a bit useless since while x < 2: ... else: print('>= 2') is the same as while x < 2: ... print('>= 2') unless you use a break. Just seems unnecessarily confusing to me. I have used for ... else though.
- deleted 8y ago[deleted]
- deleted 8y ago[deleted]
- znpy 8y agoI think that the subtle difference is that in the second example "print('>= 2')" is always executed whereas in the first example the print statements is executed only if no break was executed in the while loop. Quoting documentation: "A break statement executed in the first suite terminates the loop without executing the else clause’s suite."
- kasbah 8y agoI did say "unless you use a break". I don't think this is very useful.
- jwilk 8y agoBut... for+else without break can be rewritten the same way. And yet you claim that you've used for+else. But indeed, in my experience, while+else are much less common that for+else. I'm not sure why.
- deleted 8y ago[deleted]
- ubernostrum 8y agoAnd the full form of a Python exception handling block is not try/except/finally. It's try/except/else/finally. The 'try' block contains code which might raise an exception. It can be followed by zero or more 'except' blocks, each of which indicates the type(s) of exception it will catch and contains code to execute in the event of that type of exception. The 'except' block(s) can be followed by one 'else' block, which contains code to execute in the event no exception was raised by the code in the 'try' block. And then there is optionally a 'finally' block, containing code that must be executed in all circumstances.
- grosjona 8y agoI hate it when code uses weird niche features that are not obvious, are impossible to look up and add 0 value aside from saving a couple of lines of code.
- jkaplowitz 8y agoMe too, but this use case seems clearer than most features I'd label that way, even though I didn't know about it either. It certainly shouldn't be used when unclear, just like any feature. There's no reason this feature's sensible use cases should be as niche as they currently are.
- deathanatos 8y ago> are impossible to look up Questions about Python's syntax are anything but impossible to look up. Python has excellent documentation around this, and the steps to get to the right part of the documentation are pretty straight-forward: 1. Start at the main page, https://docs.python.org/ https://docs.python.org/ 2. Click "Language Reference"; note the subtitle that clearly hints this is what we want: "describes syntax and language elements" 3. We are interested in for loops, so we click "8.3. The for statement"; the resulting page describes the behavior.
- XorNot 8y agoAgreed. The way this ends up looking is absolutely unclear what it does - and seems like more a quirk then a feature.
- vortico 8y ago[Mistake, a moderator please delete this comment! Completely agree with the parent comment now. for...else is dumb and unintuitive. I misunderstood its function, which proves the above point to me.]
- Izkata 8y ago> The symantics of for...else are immediately obvious The code in your example is how it reads, but that's not how it works. The "obvious" reading is wrong, so it's obviously not "immediately obvious". This is what it's actually doing: found = False for l in get_list(): if ...: found = True break if not found: ...
- marban 8y agoNow I feel like I have to rewrite every single Python script I ever wrote.
- vesinisa 8y agoPlease don't bother. Obscure, very rarely used language constructs like these often don't really enhance the code's maintainability. On the contrary; would you have understood the very same code yourself before reading this article if someone else had used the construct?
- AlphaSite 8y agoI think if you read it, you'd read it and get it.
- Walkman 8y agonot really a good idea
- fratlas 8y agoI'm in favour of writing simple python that even a junior dev can read rather than using niche syntax tricks. Guess that depends on whether you think a junior should know this syntax.
- deleted 8y ago[deleted]
- ben0x539 8y agoThis is a weird response. You can definitely argue that it's bad syntactic design because people seem to expect it to do something different, but if the argument is just that some category of programmer doesn't already know what it does, you're pretty much arguing against introducing any new language feature, syntax or library that wasn't taught in your imagined CS101 or whatever.
- fratlas 8y agoI agree with your point, but I meant that I haven't seen this specific syntax in many py tutorials or projects I've read.
- ben509 8y ago> you're pretty much arguing against introducing any new language feature, syntax or library that wasn't taught in your imagined CS101 or whatever. But there clearly is a body of knowledge which you can discover yourself: you can interview candidates, read discussions on SO, read library code, and you will find some techniques are commonly used, and some are rarely used. That distribution of what's known is changing over time regardless of what we do, because our peers are constantly learning and studying at different rates. This feature has been around for years, and is so rarely used that only language mavens know about it. Thus, you can observe that this is a failed feature and avoid using it. We can always reevaluate if people understand it later on, since that could change.
- fyi1183 8y agoOn the other hand, when you do run across this construct in the wild, it is trivial to look up what it does and learn. I imagine that's how most people learned about it, since it doesn't exist in other languages. In a way I find your comment contradictory: on the one hand, you appreciate and embrace that the body of common knowledge can change. On the other hand, you use the current state of common knowledge as an argument against doing things that can improve the common knowledge.
- ageofwant 8y agoThe `else` clause follows the same general pattern wherever it supported: `for`, `while` and `try` are consistent. It usually makes code shorter or at least leads to narrowing concerns when used with `try`. For some reason I often forget to use it though.
- contravariant 8y agoOh, that didn't do what I expected at all. I was expecting this to be similar to: if list: for x in list: # Some code else: # else clause which would have been quite useful to have for general iterators. But apparently it's a statement that triggers unless you use 'break' to end the loop, which just seems like a really weird use case, and smells like a goto.
- LolWolf 8y agoThis is usually quite useful, actually! It happens a lot in numerical computing where you try a bunch of possible solutions and if none are found then you output some sort of "infeasibility" result, otherwise you output the result you broke at (skipping the else statement).
- contravariant 8y agoPutting the loop in its own function would solve the problem as well (allowing you to just return the output), or if that's not an option then you need to store the output anyway so you might as well just add a check 'if output is None:'.
- jackewiehose 8y ago> which just seems like a really weird use case I think quite the opposite: What you expected seems unnecessary to me because that is already easy to do with that if-statement in your example. On the other hand, to accomplish this "for-else" you would have to do something like this: found = false for x in list: if ...: found = true if not found: ... While writing this example I noticed that I also could make good use of the negativ: Something like for x in list: ... then: ...
- contravariant 8y agoTo achieve the for else I suggested for general generators requires a similar pattern to your suggestion so both of them save equal amounts of complexity. However I'm struggling to find a use case for the python for-else definition where you don't end up doing something like 'result=something; break' anyway. What would be the point of breaking if you don't have any results? And if you have such a situation, wouldn't an exception make more sense? Conversely to check if an iterator is non-empty you need to set a boolean to true, and you can't easily skip this part so you end up setting it to true every loop. It would have been quite nice to have an 'else' condition that triggers when the generator is empty (which also fits quite nicely with all empty containers being considered falsy).
- benwilber0 8y agoI hate adding syntax but you know what's really useful? Django's `for .. empty` template syntax. I would like to see this in Python: for i in []: print(i) empty: print("Sequence was empty!")
- askvictor 8y agoWrite up a PEP! It's a great idea. Syntax can be good if it makes sense and makes code easier to read and write.
- mixmastamyk 8y agoWon't be accepted. Recognized as a problem, but now set in stone.
- askvictor 8y agoMaybe in python 4...
- mixmastamyk 8y agoNope, been discussed many times on the lists, neither planned.
- maccam94 8y agoExcept the python "for/else" executes regardless of whether there's a sequence. I've used it before for retry logic, but it confuses the heck out of people.
- Nition 8y agoI think the user you're replying to is just saying that a for...empty would be nice too.
- rad_gruchalski 8y agoPretty convenient feature.
- jordansmithnz 8y agoTo me, the else isn’t intuitive if you haven’t encountered it before. It’s a nice feature, but perhaps better naming could improve code readability. How about for-finally? It’s a hard thing to name correctly, but to me this seems to be slightly more intuitive if you’ve never seen the feature before.
- detaro 8y agoFinally would suggest it's always executed, even if aborted, like try...finally
- makecheck 8y agoYou can’t use "finally" because that implies an expression that runs regardless, which this does not (it only runs if the loop never breaks).
- jordansmithnz 8y agoYeah, that’s a good point. To me it’s a little more clear than ‘else’ but there might be a better name still that doesn’t suggest this code always runs. Naming is hard :)
- mmebane 8y agoPerhaps `for...lastly...else`? `lastly` being the current meaning of `else` (something that happens after the iteration has completed), `else` being the thing I wish it meant (something that happens when the iterator was empty).
- deleted 8y ago[deleted]
- SamReidHughes 8y agoSince Python doesn't have goto statements, this removes one of the situations where a goto statement is the best tool to use in a language like C++.
- xapata 8y agoIn a sense, raise/except is a goto. Go-lang decided against exceptions in part because they are equivalent to gotos.
- zephyrfalcon 8y agoBut Go does have a goto statement...?
- Vendan 8y agoAnd like many languages that do, it's an extreme code smell to use it, whereas most(if not all?) languages that have exceptions recommend to use them. Though technically, Go does have exceptions (under the name "panic"), just not a very easy to use "try/catch" block (the "try/catch" stuff is function level, so you have to do anonymous functions to "emulate" other language's try/catch). Also, Go's goto has restrictions.
- SamReidHughes 8y agoIt's not really a code smell. They just don't let newbies use it in CS 101 because they want them to think in a structured manner about loops and such.
- deleted 8y ago[deleted]
- deleted 8y ago[deleted]
- askvictor 8y agoThe word else implies something different to what it does (IMHO at least). In and if/else clause, the else happens when the primary/expected thing doesn't happen. I would expect that for a loop, an else clause would happen when the loop does _not_ finish normally, or if they loop is empty. I'm sure it's a useful clause in certain cases, but the meaning of the word used is reversed. It might be better use 'then' or something like that: for i in l: print(i) then: print("iteration finished without breaking")
- jacobolus 8y agoThey probably used the word "else" to cut down on the number of reserved keywords, and for consistency with try / except / else.
- deleted 8y ago[deleted]
- kazinator 8y agoIt is consistent with the idea that it provides an alternative clause to a failing loop guard. Using the much clearer C syntax as pseudo-code, suppose we have this: for (;;) { if (loop_guard()) { body; } else { alternative; break; } } We can imagine an extension to while which lets us rewrite it like this: while (loop_guard()) { body; } else { alternative; } Based on this framing, there is justification in calling it else. The runs counter to an intuition which would like it to be this: if (loop_guard()) { while (loop_guard()) { body; } } else { alternative; } I.e. not an alternative in the face of the failed loop guard on every iteration, but just the first loop guard test: an alternative to the loop when no iterations take place.
- rlayton2 8y agoI'm a strong python advocate and rarely use for/else for this exact reason. It makes more sense to me for it to be the other way (your way) around. I always add a comment on the else when I do too, to ensure that future readers don't make the same mistake.
- mixmastamyk 8y agoYes the for...else is useful but for years it didn't do what I expected, which is execute when the sequence was empty. After reading the docs a half dozen times I finally internalized that the else actually means "not broken," aka "not found." So now when I use it, I always put a comment next to it for myself and the next person: for item in items: if found: break else: # no-break print('not found.')
- deleted 8y ago[deleted]
- deleted 8y ago[deleted]
- kazinator 8y agoIn fact, what it means is "execute this else when the loop guard fails" (regardless of whether the loop body has executed at all, or how many times). It is a legitimate alternate clause in the sense that it provides alternative behavior when the guard fails. Except when the loop is infinite, or is broken prematurely, the loop guard will fail. Under for item in list, the implicit guard fails immediately when the list is empty. If the list isn't empty, it fails after the last item is iterated upon. Thus here it also means "else if there are no more items to be processed".
- acqq 8y ago> It is a legitimate alternate clause in the sense that it provides alternative behavior when the guard fails. But the "guard fails" and the else is executed on every normal loop exit, except if the exit was done with break. for a in range( 1,3 ): print( a ) else: print( "end" ) gives: 1 2 end It's an "alternative" only when there's break. In all other cases it is executed. Even naming it "nobreak" would be confusing as without break it is always executed at the end. The clearer naming would be approximately "on_every_nonbreak_end_of_for"
- iamforreal 8y agoHonestly, I would just not use it wherever possible. It's a wart on the language, and there are plenty of semantically superior alternatives. I would rather wrap in function + use return over break, use a sentinel value, or raise an exception over using the else block. If there's anything I've learned, it's that just because a language has a feature, doesn't mean it should be used.
- eigenvalue 8y agoThe fact that so many commenters here are confused or surprised by what it means or how it works sort of proves to me that it is a bad idea to use this in your code-- especially if anyone else might need to work on that code. I always prefer the clearer, obvious approach, even it is slightly longer.
- Myrmornis 8y agoI agree that many people find it surprising/ bad syntax. I’m one of them, I have to think and double think every time I consider using it. But it’s part of the language, and we should embrace our language that we use.
- kbumsik 8y agoIt is true that this is confusing for people who come across it for the first time, but it is easy to understand/remember once you know this feature.
- genidoi 8y agoA counter-intuitive feature is not worth using even if 9/10 python devs know about it. Which they don't seem to. https://twitpic.com/4a52sh https://twitpic.com/4a52sh Seems like bad usability.
- jbclements 8y agoanother reason to dislike Python, sigh.
- makecheck 8y agoWhile this is a great capability to have, the tendency to have an indented “if” preceding a not-indented “else” just always seems like somebody might have made a mistake. I would rather something that captures the loop state itself as an operable object, such as: with for as loop: for x in my_list: ... if not loop.broken: ...
- sooheon 8y agoInteresting how people's intuitions differ. For me hiding yet another . method that requires discovery is more burden on the human. I'd rather reach for map/filter => processing.
- Mangalor 8y agoSeconded
- deleted 8y ago[deleted]
- fyi1183 8y agoThe if you're talking about ends in a break. To me and many others, having an else associated to an if that ends in break/continue/return is a code smell, because it misleadingly suggests that there are two possible paths of control flow that reach the code after the if/else, when in reality you can only reach that point through the else block.
- nickm12 8y agohttps://twitpic.com/4a52sh https://twitpic.com/4a52sh A survey on this feature was done at Pycon 2011. Maybe things have changed since then, but at the time, most people didn't understand what for/else did. I think it's a bad construct because, as many have mentioned, a lot of people make the commonsense interpretation that the else block will only execute if the for block did not. Note, the link above come via Jeremy Avnet in the comments of this blog post. https://nedbatchelder.com/blog/201110/forelse.html https://nedbatchelder.com/blog/201110/forelse.html
- mar77i 8y agoPersonally, I'm really struggling with the idea which is underlying to this feature, and I find it relieving to find this article and survey result. - Does the else realize that the loop contains an if block? - How does a break statement relate to the StopIteration exception? - How does the else block run if the range wasn't, technically, empty?
- rplnt 8y ago> the commonsense interpretation that the else block will only execute if the for block did not That is exactly what it does. So when you explicitly break, the for body was executed. As for the poll, the first answer is not wrong. It's first option even, the question is vague enough. I wouldn't read that much into it, 33+24+9 (66%) people gave correct answer.
- irishsultan 8y agoExcept it isn't what it does. What that option means is that either the loop is entered, or else if the condition is false from the start it will execute the else block.
- rplnt 8y agoIt is what it does. It's not all it does, but the option is correct. Only when looking at other options you would notice there is one that is "more" correct. It's not a poll you can draw any conclusions from. That being said, if you look around, pretty much everyone agrees it is a confusingly implemented feature. I don't think there's any question about that. But at the same time you can find explanations why it is named the way it is, and that can help to remember it better.
- zmmmmm 8y agoNearly everybody seems surprised by what it does, which would appear to constitute a fairly strong violation of the "principle of least surprise" that is one of the most cited guiding principles employed by the designers of Python. As such it would seem better to be described as an "anti-tip" or something like that.
- eesmith 8y agoIt was a feature van Rossum added in the earliest days of Python, on 14 Oct 1990, back before he fully developed his design sense. As I recall, he said added it because the implementation structure of the "for" code matched the implementation structure of the "if" code, and he felt that 'for' could use an 'else'.
- deleted 8y ago[deleted]
- AlexCoventry 8y agoI'm curious why people are interested in this. No way I would have predicted it would get to the top of HN.
- mychael 8y agoNever use this in the real world please.
- reuven 8y agoI love Python's for-else feature. I've used it on a number of occasions, and have found it to be useful and to cut down on code. However, I agree that the use of "else" is horribly confusing. When I teach "for-else" to students in my Python courses, they are often surprised by the functionality, and doubly surprised that the word "else" is used. I often joke that it would be a great feature, if only they had chosen something a bit more intuitive and memorable instead of "else", such as "if_we_exited_the_block_without_encountering_a_break". Slightly more seriously: While I realize that adding a keyword to Python isn't in the cards, a word such as "nobreak" would be easier for people to understand, and would stress the point of the functionality. The fact that Emacs always tries to indent the "else" of a "for-else" to align with an "if" inside of the loop, rather than the "for" with which it matches, speaks volumes. I mean, if Emacs is confused, then how are we mere mortals supposed to remember? So when I use "for-else", it's almost always in code that I am writing for myself, and that I don't expect others to read or maintain. Don't forget that there's also "while-else", although I can't remember the last time I saw that actually used.
- 2T1Qka0rEiPr 8y agoAgree with everything here! As a Python novice I found the name terrible, but nowadays I make use of it pretty frequently, and like the power which comes with it. I also use `try-except-else` (though I appreciate the "else" here has completely different semantics, I think it's something few people know about)
- toxik 8y agoI would definitely expect a human to understand code intent (and indent) better than Emacs. Machine learning has some ways to go still. ;-)
- monsieurbanana 8y agoEmacs is really not a reference in terms of code indentation. I expect classic IDE to be much more robust at it, since emacs uses regex most of the time to determine indentation (the javascript mode is the only exception I remember), whereas I imagine a full-blown python IDE will actually parse the code.
- SmirkingRevenge 8y agoI've used the loop -> else construct sparingly - there are times when it is really convenient. But it is VERY confusing. Its very confusing, and poor design - IMHO - because the presence of an "else" block, in the typical case, generally indicates that the preceding block was never executed. When it comes to while/for blocks in python, the keyword literally indicates the opposite - that the preceding block executed without hiccups - and so also execute this block. Its a great feature - but there should have been another keyword for it: "also" (or something like that)
- wwwtyro 8y agoHold up. Stop. Read the parent closely. This is a case where the right answer is only obvious once it's been stated. > Its a great feature - but there should have been another keyword for it: "also" SmirkingRevenge - !@#$ing brilliant. You've stepped outside the box and presented an answer that will click as soon as it's read. Someone make a PEP.
- hueving 8y ago"nobreak" also makes as much sense. Even Raymond Hettinger has suggested that, but getting a new keyword at this point in python is going to be really difficult.
- SmirkingRevenge 8y ago"nobreak" also works, and arguably has less ambiguity than my suggestion. And I agree getting a new keyword for such a limited use-case feature would be difficult and doesn't feel likely.
- gvx 8y agoHonestly, "else" wasn't confusing to me at all, but "also" would make me very confused.
- SmirkingRevenge 8y agoThat may be the nicest reply I've ever had on HN. Thanks!
- deleted 8y ago[deleted]
- jacob019 8y agoI've been using this for years and never thought twice about it, I'm shocked by all the negativity. It's great for controlling iteration in a nested loop: for item in report(): for event in in item['events']: if event in events_we_care_about: break else: continue act_upon(item) I realize it's a trivial example that could be written without a nested loop, but there are often good reasons for nested loops and littering them with control variables and if statements gets messy quick. I have always found for-else to produce more elegant code. Your criticisms may be quite valid, I just wanted to share my surprise.
- ankrgyl 8y agoI may be missing something... but how is that clearer than for item in report(): for event in item['events']: if event in events_we_care_about: act_upon(event) break
- jacob019 8y agoIt's a trivial example. Just to demonstrate how for else helps to control an outer loop from within an inner loop.
- rahimnathwani 8y agoYour act_upon is passed values from the inner loop. GP's act_upon is passed values from the outer loop.
- Asooka 8y agoI would write that as for item in report(): if any(event in events_we_care_about for event in item['events']): act_upon(item) But obviously the features that enable this form didn't exist when for...else was added to the language.
- jacob019 8y agoClearly it was a poor example, I wouldn't structure simple code this way either but in more complex situations it can be the simplest solution.
- random_throw 8y agoThis is discussed as item 12 in Effective Python. The author argues that you should avoid "else" blocks after "for" and "while" loops. The main argument is that the behavior is not intuitive and could be confusing upon reading given its somewhat obscure usage. He suggests using a helper function with an early exit or setting a result variable and using a break in your loop instead.
- hiccuphippo 8y agoI had my first legitimate use of for else last week after knowing about it for years and it (the keyword) never making much sense. I had to call an API for it to load data into a cache, but sometimes this wouldn't work so I made it try up to 3 times, otherwise it would show an error. So something like: for i in range(3): if load_cache(): log("success") break else: log("failure") Else made total sense here.
- quickthrower2 8y agoElse is a bit of a confusing name for the keyword IMO. How about "ifcompleted"
- cup-of-tea 8y agoFor-else is nothing. The really weird one is the Try-else. The For/While-else does exactly what I expect. I'm not sure why others find it confusing. The Try-else does make some code more readable but is quite rare I would say.
- Vendan 8y agoWell, for one thing, a few templating engines have a "for each item, print x, else if there are no items, print y". (for instance: https://handlebarsjs.com/builtin_helpers.html#iteration https://handlebarsjs.com/builtin_helpers.html#iteration)
- cup-of-tea 8y agoThat's not intuitive at all. That's equivalent to: if len(items) == 0: print(y) else: for item in items: print(item) Which means there's a whole extra implicit if. The for in Python is really this: it = iter(items) while True: try: item = next(it) except StopIteration: print("else") break print(item) Where that try/except is like "if there is a next item do this, else do this", hence: for item in items: print(item) else: print("else")
- Vendan 8y agoNever said intuitive, but that construct is EXTREMELY useful for things like "no results found" and such, when a list of items is empty. Therefore, it is usually explained quite early and used often in template languages that have it. This is the first time I've seen python's, after dealing with several large codebases written in python.
- blumomo 8y agoI find this pattern very much better expressed with functional programming: item = next((item for item in container if search_something(item)), None) if item: process(item) else: not_found_in_container() instead of as suggested in the blog post: for item in container: if search_something(item): # Found it! process(item) break else: # Didn't find anything.. not_found_in_container()
- gvx 8y agoYour suggestion contains bugs, though. To make it fully equivalent to the code in the blog post, it would need to be: sentinel = object() item = next((item for item in container if search_something(item)), sentinel) if item is not sentinel: process(item) else: not_found_in_container() ... because item could be None or another falsy value.
- hajderr 8y agoThis is strongly advised against in the book Effective Python as the semantics are opposite to what one is used to. The else clause will always be executed unless there's a 'break' in the for-loop.
- m4r71n 8y agoOne thing that for-else is very useful for is implementing an elegant and easy-to-understand retry mechanism: for _ in range(3): success = do_something() if success: break else: raise FailedToDoSomething I generally like this feature of the for loop and it would be a shame if it was removed.
- cup-of-tea 8y agoIndeed I have use this idiom a lot. The alternative is to store a state variable indicating success which isn't very nice.
- kidgabi 8y agoSpotify officially announced its own student discount a long while ago – there is a 50% discount on Spotify. https://techindroid.com/get-spotify-student-plan-discount/ https://techindroid.com/get-spotify-student-plan-discount/
- OJFord 8y agoI much more frequently wish that I could express 'or do this if zero iterations' than I use for-else as it is; I do so wish it had the former semantic. That and the absence of do-while are the cause of a good deal of non-DRY python around loops.
- nearmuse 8y agoOr maybe it was a terrible "or else" pun that does not deserve much discussion.
- bjourne 8y agoThis is coincidentally my highest rated Stackoverflow answer ever. :) https://stackoverflow.com/questions/9979970/why-does-python-use-else-after-for-and-while-loops https://stackoverflow.com/questions/9979970/why-does-python-... Tl;dr my highly opinionated opinion is that one should never use the construct
- pure_ambition 8y agoWell, that’s a dumb feature. Very counterintuitive, requires you to stop and think, and there’s a high probability that it’ll be misunderstood at first glance. I hate things like this - you’ll read it, think you understand it, experience a bug, spend hours debugging, then finally look up the documentation for ‘else’ and see that it means something different from what you thought.
- julienfr112 8y agoI write quite often something like that: for i in range(10): for j in range(10): if condition(i,j): dosomething break else: continue break It's a pattern that ensure that dosometing is run at most once by "propagating" the break to the outer loop. The alternative is use a function and do a return. Any though of this ?
- alkonaut 8y agoI'm not a python programmer but I find the last 4 lines rather hard to read. Unless there is a performance reason to not do so, I'd argue that you are iterating over pairs (i,j) here and I'd make the code clear. There are 100 pairs, and once you find one that satisfies the condition you are done. Again, not a python programmer but it might look like (x, y) for x in range(10) for y in range(10) if condition(i,j) dosomething; break; Edit, ("zip" is not the outer product... )
- quietbritishjim 8y agoThe relevant function is itertools.product() [1]. It can give the Cartesian product of arbitrary iterables, but if you have the same iterable more than once, as in this example, you can take advantage of the repeat= optional parameter to simplify the call a little bit: for x, y in itertools.product(range(10), repeat=2): if condition(x, y): dosomething(x, y) break Alternatively, you can use Python list comprehensions: prodlist = [x, y for x in range(10) for y in range(10)] for x, y in prodlist: if condition(x, y): dosomething(x, y) break Overall, I still prefer refactoring into a function and using return, as the GP comment suggested. [1] https://docs.python.org/3/library/itertools.html#itertools.product https://docs.python.org/3/library/itertools.html#itertools.p...
- holografix 8y agoI would never include this in my code. It’s a construct most devs have never seen in Python and it differs from anything I’ve seen in other languages. Always KISS.
- joshmkay 8y agoI can't see this ever being used. As a non-python programmer, if I ran across this it would be very confusing. If it's simple enough to write the same code without the else block and have your code be more readable, why not do that?