Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Post History

60%
+1 −0
Q&A Tips for golfing in Python

Combine loops Suppose you have a for loop in another, maybe a couple of times, and nothing else inside of the outer for loops (except for the first for loop since anything outside won't be involve...

posted 3y ago by General Sebast1an‭

Answer
#1: Initial revision by user avatar General Sebast1an‭ · 2021-09-12T00:19:54Z (about 3 years ago)
# Combine loops

Suppose you have a `for` loop in another, maybe a couple of times, and nothing else inside of the outer `for` loops (except for the first `for` loop since anything outside won't be involved at all). It's probably a `range()` problem again.

If you're doing something like this:
<!-- language-all: lang-python -->

<pre><code>x=10;y=15
for i in range(x):
&#9;for j in range(y):
&#9;&#9;print(i,"-",j)
</code></pre>

[Try it online!][TIO-ktfugtxg]

[TIO-ktfugtxg]: https://tio.run/##K6gsycjPM/7/v8LW0MC60tbQlCstv0ghUyEzT6EoMS89VaNC04qLEySWhRCrBIlxFhRl5pVoZOoo6SrpZGn@/w8A "Python 3 – Try It Online"

You can simply set the loop as one:
<!-- language-all: lang-python -->

    x=10;y=15
    for i in range(x*y):print(i//y,"-",i%y)

[Try it online!][TIO-ktfujaan]

[Python 3]: https://docs.python.org/3/
[TIO-ktfujaan]: https://tio.run/##K6gsycjPM/7/v8LW0MC60tbQlCstv0ghUyEzT6EoMS89VaNCq1LTqqAoM69EI1Nfv1JHSVdJJ1O1UvP/fwA "Python 3 – Try It Online"

Golfing 16 bytes in total. You can do this with more loops, but this is what's functional for now.