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:
You can separate statements with semicolons on a single line:
for i in range(5): print(i); print(i * 2)
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)]
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)]
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.