Skip to content

Instantly share code, notes, and snippets.

@Epivalent
Created July 10, 2024 14:54
Show Gist options
  • Save Epivalent/9332dfa3098e4cc65877f693f0313187 to your computer and use it in GitHub Desktop.
Save Epivalent/9332dfa3098e4cc65877f693f0313187 to your computer and use it in GitHub Desktop.

In Python, the standard way to write a for loop involves using newlines and indentation to define the block of code that should be executed within the loop. However, if you want to avoid newlines and indentation for some reason (e.g., fitting everything on one line), you can use a combination of semicolons (;) and list comprehensions or generator expressions.

Here are a few ways to achieve this:

Using Semicolons

You can separate statements with semicolons on a single line:

for i in range(5): print(i); print(i * 2)

Using List Comprehension

If your goal is simply to execute an expression for each item in an iterable, you can use list comprehension:

[print(i) for i in range(5)]

Using Generator Expression with next()

For more complex operations where you need multiple statements inside the loop body, you might consider using a generator expression combined with exec() or defining functions inline. This approach is quite hacky and not recommended for production code due to readability concerns:

def process_item(i):
    print(i)
    print(i * 2)

[process_item(i) for i in range(5)]

Or using lambda functions (though this is even less readable):

[(lambda x: (print(x), print(x * 2)))(i) for i in range(5)]

Using exec() Function

Another hacky way is using the exec() function, but it’s generally discouraged due to security risks and poor readability:

exec("for i in range(5): print(i); print(i * 2)")

While these methods allow you to write loops without traditional newlines and indentation, they often sacrifice readability and maintainability. It's usually best practice to stick with Python's conventional syntax unless there's a compelling reason not to.

Wed 10 Jul 16:54:41 CEST 2024 - is there some hacky way to do a python3 for loop without using newlines and indentation?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment