The loop itself is perfectly fine. One small optimization you could do is with your if/else statement however; for i, day in enumerate(week): week_fmt.append(day) if i < 5: # Duplicate first 5 days week_fmt.append(day) Could you turn this into a one-liner? Probably. Should you want to? Absolutely not. You'd just make things more complicated than they need to be, and maybe more importantly, no one will be able to understand what you wrote. As a side note, I am kinda curious what the purpose of this week_fmt list is. I have a feeling that what you're doing can be achieved more easily. If you want, briefly explain what this loop is for, and we may still be able to make a clean one-liner after all. Answer from DutchCommanderMC on reddit.com
Discussions

'for' loop in one line in Python - Stack Overflow
For the Step 3 we just need to ... a single line using list comprehension, then we can fit that in a lambda function or inside the return statement of a function. ... Sign up to request clarification or add additional context in comments. ... Perhaps, you are looking for list comprehension, which is a way to generate lists, when the loop body only ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
how about one-line try-except statement ?
It fits a little awkwardly with "there should be one, and ideally only one, obvious way to to it". I know this was part of the reason they held off adding ternary operators on the early days (although of course they have them now). Speaking for myself, I can't think of many times when I've worked with code that this would help with. And I know they don't like to add language syntax unless it solves quite a lot of people's problems well. For something like your use case, where you're dealing with a common and expected case, it would be common to have an alternate method that returns a sentinel value. And indeed there is such a method, str.find. More on reddit.com
๐ŸŒ r/Python
6
1
June 14, 2024
How can I write this for loop in one line?
The loop itself is perfectly fine. One small optimization you could do is with your if/else statement however; for i, day in enumerate(week): week_fmt.append(day) if i < 5: # Duplicate first 5 days week_fmt.append(day) Could you turn this into a one-liner? Probably. Should you want to? Absolutely not. You'd just make things more complicated than they need to be, and maybe more importantly, no one will be able to understand what you wrote. As a side note, I am kinda curious what the purpose of this week_fmt list is. I have a feeling that what you're doing can be achieved more easily. If you want, briefly explain what this loop is for, and we may still be able to make a clean one-liner after all. More on reddit.com
๐ŸŒ r/learnpython
11
8
January 1, 2024
how do i print while loop outputs on the same line?

Alternatively...

Instead of printing in the loop, append what you want to print to a list.

Then AFTER the loop, print out the entire list. Something like join() is great for inserting commas without needing to have a special case for "except after the last one".

result = []
for idx in range(10):
    result.append("n{}".format(idx))
print(",".join(result))
More on reddit.com
๐ŸŒ r/learnpython
18
7
June 3, 2020
๐ŸŒ
Treehouse Blog
blog.teamtreehouse.com โ€บ python-single-line-loops
Simplify Your Python Loops with Comprehensions [Tutorial] | Treehouse Blog
September 10, 2025 - Way better than the python documentation. 10 thumbs up! ... Hi, anyone have an idea how to make this faster? [f(x,y) for x in range(1000) for y in range(x, len(range(1000)))]? ... Sometimes it is convenient to use single line for loops as follows: for act in actions: act.activate() ... Nicely structured introduction. Thank you. BTW first worked example: my_doubled_list = list_doubler(lst) s/b my_doubled_list = list_doubler(my_list) ... Nice one Ken.
๐ŸŒ
Medium
medium.com โ€บ @andrewdass โ€บ python-how-to-make-and-use-single-line-for-loops-3dbadb2ab811
Python: How to Make and Use Single Line For Loops | by Andrew Dass | Medium
January 22, 2025 - In a one line for loop statement, the variable is written first and then the for loop statement. ''' Below shows the variable numbers_in_a_list is assigned to data that is casted within a list ''' numbers_in_a_list = [number for number in range(1, ...
๐ŸŒ
Finxter
blog.finxter.com โ€บ home โ€บ learn python blog โ€บ python one line for loop [a simple tutorial]
Python One Line For Loop [A Simple Tutorial] - Be on the Right Side of Change
March 23, 2024 - Just writing the for loop in a single line is the most direct way of accomplishing the task. After all, Python doesnโ€™t need the indentation levels to resolve ambiguities when the loop body consists of only one line.
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ python โ€บ one line for loop python
One-Line for Loop in Python | Delft Stack
February 22, 2025 - Learn how to write one-line for loops in Python using list comprehensions, dictionary comprehensions, and more. This guide covers syntax, benefits, and real-world examples to help you write clean, efficient, and optimized Python code. Perfect for beginners and advanced programmers alike!
Find elsewhere
๐ŸŒ
GoLinuxCloud
golinuxcloud.com โ€บ home โ€บ python โ€บ python for loop in one line explained with easy examples
Python for loop in one line explained with easy examples | GoLinuxCloud
January 9, 2024 - The simple python for loop in one line is a for loop, which iterates through a sequence or an iterable object. We can either use an iterable object with the for loop or the range() function.
Top answer
1 of 3
30

 Solution

If you strictly want a one-liner, then this is the solution:

get_cubes = lambda x: [pow(i, 3) for i in range(0, x+1, 3)]

But since clarity and readability should always be a priority in Python, it's better to write it as a function just like @daniel did:

def get_cubes(x):
    return [pow(i, 3) for i in range(0, x+1, 3)]

 Output

Using a for loop to test the function you get the following results:

for i in range(20):
    print(i, ':', get_cubes(i))

0 : [0]
1 : [0]
2 : [0]
3 : [0, 27]
4 : [0, 27]
5 : [0, 27]
6 : [0, 27, 216]
7 : [0, 27, 216]
8 : [0, 27, 216]
9 : [0, 27, 216, 729]
10 : [0, 27, 216, 729]
11 : [0, 27, 216, 729]
12 : [0, 27, 216, 729, 1728]
13 : [0, 27, 216, 729, 1728]
14 : [0, 27, 216, 729, 1728]
15 : [0, 27, 216, 729, 1728, 3375]
16 : [0, 27, 216, 729, 1728, 3375]
17 : [0, 27, 216, 729, 1728, 3375]
18 : [0, 27, 216, 729, 1728, 3375, 5832]
19 : [0, 27, 216, 729, 1728, 3375, 5832]

Explanation

For those who asked why @daniel's code work:

The original code does the following:

  1. Given an x, iterate from 0 to the number of times 3 divides x plus 1.
  2. For each x, multiply it by 3 and raise it to the power of 3
  3. Return the list containing the results of step 2

Step 1 was originally written as

range(int((x - x%3) / 3) + 1)

which subtracts the reminder of a number when divided by 3 and then divides that result by 3 before adding 1. But the same result can be achieved by just getting the integer part of dividing x by 3 and then adding 1 which will look something like this:

int(x / 3) + 1

Step 2 multiplies each iteration by 3 before raising it to the power of 3 but that "multiplication" can be achieved as well by using ranges (just like @daniel did) using:

range(0, x+1, 3)

which iterate from 0 to x+1 on steps of 3 and yields the same results. I.e x being 10:

range(0, 10 + 1, 3)  |    i*3 for i in range(int(x / 3) + 1)
============================================================
0                    |    0*3 = 0
3                    |    1*3 = 3
6                    |    2*3 = 6
9                    |    3*3 = 9

For the Step 3 we just need to apply pow(x, 3) (or x ** 3) and we can fit everything in a single line using list comprehension, then we can fit that in a lambda function or inside the return statement of a function.

[pow(i, 3) for i in range(0, x+1, 3)]
2 of 3
7

The correct syntax for for-loops is

def get_cubes(x):
    ls = []
    for item in range(int((x-x%3)/3)+1):
        ls.append(pow(item*3, 3)) 
    return ls

Perhaps, you are looking for list comprehension, which is a way to generate lists, when the loop body only appends to a list:

def get_cubes(x):
    ls = [(item*3) ** 3 for item in range(int((x-x%3)/3)+1)]
    return ls

or in short:

def get_cubes(x):
    return [i ** 3 for i in range(0, x+1, 3)]
๐ŸŒ
Python
wiki.python.org โ€บ moin โ€บ Powerful Python One-Liners
Powerful Python One-Liners
July 19, 2023 - Some day, I will add a detailed explanation here - but for now, you can read this blog article to find explanations. 1 # Palindrome Python One-Liner 2 phrase.find(phrase[::-1]) 3 4 # Swap Two Variables Python One-Liner 5 a, b = b, a 6 7 # Sum Over Every Other Value Python One-Liner 8 sum(stock_prices[::2]) 9 10 # Read File Python One-Liner 11 [line.strip() for line in open(filename)] 12 13 # Factorial Python One-Liner 14 reduce(lambda x, y: x * y, range(1, n+1)) 15 16 # Performance Profiling Python One-Liner 17 python -m cProfile foo.py 18 19 # Power set Python One-Liner 20 lambda l: reduce(la
๐ŸŒ
Medium
medium.com โ€บ @chenyumei8866 โ€บ 20-extremely-useful-single-line-python-codes-bc553ea4832a
20 extremely useful single-line Python codes | by Python Data Development | Medium
January 8, 2023 - Now you no longer need to use a for loop to print the same pattern. You can use the print statement and asterisk (*) to do the same thing in a single line of code. # One line print pattern# # Single-line method for x in range(3): print('๐Ÿ˜€') ...
๐ŸŒ
sebhastian
sebhastian.com โ€บ python-one-line-for-loop
Python one line for loop tutorial | sebhastian
February 22, 2023 - Suppose you have a for loop as ... print(i); print("End") But keep in mind that writing a single line for loop goes against Python conventions of one statement per line....
๐ŸŒ
LinkedIn
linkedin.com โ€บ pulse โ€บ python-how-make-use-single-line-loops-andrew-dass-vdxae
Python: How to Make and Use Single Line For Loops
January 22, 2025 - In a one line for loop statement, the variable is written first and then the for loop statement. ''' Below shows the variable numbers_in_a_list is assigned to data that is casted within a list ''' numbers_in_a_list = [number for number in range(1, ...
๐ŸŒ
Verve AI
vervecopilot.com โ€บ interview-questions โ€บ can-python-one-line-for-loop-be-the-secret-weapon-for-acing-your-next-interview
Can Python One Line For Loop Be The Secret Weapon For Acing Your Next Interview
The python one line for loop, often referred to as a list comprehension, set comprehension, or dictionary comprehension, is a syntactic construct that allows you to create lists, sets, or dictionaries in a single line of code.
๐ŸŒ
Sololearn
sololearn.com โ€บ en โ€บ Discuss โ€บ 2539618 โ€บ solved-how-to-write-for-loop-in-one-line-
[SOLVED] How to write for loop in one line ? | Sololearn: Learn to code for FREE!
I also suggest this way: [[sum:=0],[sum:=sum+int(c) for c in "123"],[print(sum)]] for this programm: sum=0 for c in "123": sum=sum+int(c) print(sum) because it is more generall and can also used to doe everything within this for loop and also ...
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ python-one-liners
Python One-Liners to Help You Write Simple, Readable Code
November 28, 2023 - On the other hand, list comprehension can achieve the same result in a single line, making the code more concise and readable. It condenses the loop into a clear, compact structure, generating the squared numbers directly into a list. # Using list comprehension squared_numbers = [i ** 2 for i in range(10)] print(squared_numbers)
๐ŸŒ
Kaggle
kaggle.com โ€บ code โ€บ rhythmcam โ€บ python-basic-one-line-double-for-loop
[python Basic]One Line Double for loop
Checking your browser before accessing www.kaggle.com ยท Click here if you are not automatically redirected after 5 seconds
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-for-loops
Python For Loops - GeeksforGeeks
This code uses a for loop to iterate over a string and print each character on a new line. The loop assigns each character to the variable i and continues until all characters in the string have been processed.
Published ย  2 weeks ago