Change print item to:

  • print item, in Python 2.7
  • print(item, end=" ") in Python 3

If you want to print the data dynamically use following syntax:

  • print(item, sep=' ', end='', flush=True) in Python 3
Answer from ewall on Stack Overflow
Top answer
1 of 16
565

Change print item to:

  • print item, in Python 2.7
  • print(item, end=" ") in Python 3

If you want to print the data dynamically use following syntax:

  • print(item, sep=' ', end='', flush=True) in Python 3
2 of 16
177

By the way...... How to refresh it every time so it print mi in one place just change the number.

In general, the way to do that is with terminal control codes. This is a particularly simple case, for which you only need one special character: U+000D CARRIAGE RETURN, which is written '\r' in Python (and many other languages). Here's a complete example based on your code:

from sys import stdout
from time import sleep
for i in range(1,20):
    stdout.write("\r%d" % i)
    stdout.flush()
    sleep(1)
stdout.write("\n") # move the cursor to the next line

Some things about this that may be surprising:

  • The \r goes at the beginning of the string so that, while the program is running, the cursor will always be after the number. This isn't just cosmetic: some terminal emulators get very confused if you do it the other way around.
  • If you don't include the last line, then after the program terminates, your shell will print its prompt on top of the number.
  • The stdout.flush is necessary on some systems, or you won't get any output. Other systems may not require it, but it doesn't do any harm.

If you find that this doesn't work, the first thing you should suspect is that your terminal emulator is buggy. The vttest program can help you test it.

You could replace the stdout.write with a print statement but I prefer not to mix print with direct use of file objects.

🌐
Spark By {Examples}
sparkbyexamples.com › home › python › how to write python for loop in one line?
How to Write Python For Loop in One Line? - Spark By {Examples}
May 31, 2024 - # Write For loop in one line # to iterate through a list # Initialize the list my_list = ["Python", "Pandas", "Spark", "PySpark"] print("My list :", my_list) for item in my_list: print(item)
Discussions

Python: for loop - print on the same line - Stack Overflow
I have a question about printing on the same line using for loop in Python 3. I searched for the answer but I couldn't find any relevant. So, I have something like this: def function(s): re... More on stackoverflow.com
🌐 stackoverflow.com
python - Use one line of code to print a for loop - Stack Overflow
I have a list of strings stored in results that I want to print one at a time to look like this: String 1 String 2 String 3 etc. Right now, I have this, which works fine: for line in results: ... More on stackoverflow.com
🌐 stackoverflow.com
python - Print and for loop in one line - Stack Overflow
If you want to print the results line by line just use extended iterable unpacking operator. More on stackoverflow.com
🌐 stackoverflow.com
Changing output to only one line
Hello, I’m still a beginner to Python coding. Currently, I’m stuck at this part where I’m trying to generate ONLY one line of output that contains the answers. Instead of repeating the ‘Vowels are:’ output, I want my output to just be: Vowels are: [ans1] [ans2] … Also, my side question ... More on discuss.python.org
🌐 discuss.python.org
0
0
March 28, 2022
🌐
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, ...
🌐
Bobby Hadz
bobbyhadz.com › blog › python-print-for-loop-in-one-line
How to Print on the Same Line in Python | bobbyhadz
Copied!my_list = ['bobby', 'hadz', 'com'] # ✅ print list items horizontally in for loop for item in my_list: print(item, end=' ') # 👉️ bobby hadz com # ------------------------------------------- # ✅ print horizontally using iterable unpacking print(*my_list) # 👉️ bobby hadz com # ------------------------------------------- # ✅ print horizontally using str.join() result = ' '.join(my_list) print(result) # 👉️ bobby hadz com
🌐
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 - There are two ways of writing a one-liner for loop: Method 1: If the loop body consists of one statement, simply write this statement into the same line: for i in range(10): print(i).
🌐
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 - Now let us take one more example of one line for loop to understand everything clearly. Let us say we have the following simple for loop which gives the square of only odd numbers from 1 to 10. # simple for loop for i in range(1, 10): # checking if number is even if i%2==0: pass else: # printing square print(i*i) ... Now let us use python for loop in one line to print the square of all odd numbers from 1 to 10 using the same logic.
Find elsewhere
🌐
Python Forum
python-forum.io › thread-14264.html
Python-for loop print into single line
Code bellow prints each line for multiple output. Is it possible to print this output into single line: reservations = ec.describe_instances().get('Reservations', []) for reservation in reservations: for instance in reservation['Inst...
🌐
Sololearn
sololearn.com › en › Discuss › 2119333 › how-to-make-the-output-of-for-loop-to-be-in-one-line-and-not-on-different-lines
How to make the output of for loop to be in one line and not on different lines | Sololearn: Learn to code for FREE!
January 1, 2020 - print("".join(r), end = " ") By default print() ends the printing session with a new line character, which moves the cursor position to the next line. Customising the 'end' value with a space makes print() ends the printing session with a space.
🌐
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.
🌐
Scaler
scaler.com › home › topics › how to print in same line in python?
How to Print in Same Line in Python? - Scaler Topics
May 4, 2023 - As far as we know that in a for loop, the print command runs for n times, then every time it will print the content in a new line, but if we use end = " ", then we print the content in a single line, but also we are using for loop in that case.
🌐
Sololearn
sololearn.com › en › Discuss › 2336541 › solved-how-to-use-for-loop-and-if-statement-in-one-line
[solved] How to use for loop and if statement in one line?? | Sololearn: Learn to code for FREE!
a=[i+1 if i%2==0 else i-1 for i in range(10)] print (a) For loop and if else statements written in one line using list comprehension methods
🌐
Javatpoint
javatpoint.com › how-to-print-in-same-line-in-python
How to print in same line in Python - Javatpoint
How to print in same line in Python with python, tutorial, tkinter, button, overview, entry, checkbutton, canvas, frame, environment set-up, first python program, basics, data types, operators, etc.
🌐
EyeHunts
tutorial.eyehunts.com › home › print for loop in one line python | example code
Print for loop in one line python | Example code - EyeHunts
October 22, 2021 - Write a For Loop in a Single Line of Python Code example, Compress Two Lines in One Line (print from 0 to 9) and List Comprehension
Top answer
1 of 4
4

As Jon and Patrick mention, that's not an error, it's what happens when you print the __repr__ of a generator expression.

So you just need to "splat" that generator. :)

print(*(i**2 for i in range(int(input()))), sep='\n')

demo output

10
0
1
4
9
16
25
36
49
64
81

In that demo I entered 10 at the input prompt.


In the comments I wondered how the speed of i * i compares to i ** 2. On my old 2GHz 32 bit single core machine, running Python 3.6.0, i * i is around 3 or 4 times faster than i ** 2. Here's some timeit code.

from timeit import Timer

commands = {'mul' : 'num * num', 'pow' : 'num ** 2'}

def time_test(num, loops, reps):
    timings = []
    setup = 'num = {}'.format(num) 
    for name, cmd in commands.items():
        result = Timer(cmd, setup).repeat(reps, loops)
        result.sort()
        timings.append((result, name))

    timings.sort()
    for result, name in timings:
        print(name, result)

loops, reps = 100000, 3
num = 1
for _ in range(10):
    print('num =', num)
    time_test(num, loops, reps)
    num <<= 1

output

num = 1
mul [0.02114695899945218, 0.02127135100090527, 0.02303983199817594]
pow [0.08504067399917403, 0.08687452600133838, 0.12349813100081519]
num = 2
mul [0.02089159800016205, 0.021789606998936506, 0.02889108999806922]
pow [0.08612996800002293, 0.09132789800059982, 0.09559987299871864]
num = 4
mul [0.021155500999157084, 0.02333696799905738, 0.028521009000542108]
pow [0.08492234799996368, 0.08499632499660947, 0.08537705599883338]
num = 8
mul [0.02173021600174252, 0.021955170999717666, 0.02823427400289802]
pow [0.08423048700205982, 0.08541251700080466, 0.08654486299928976]
num = 16
mul [0.02176373900147155, 0.02222509399871342, 0.02816650199747528]
pow [0.08528696699795546, 0.09080051600176375, 0.0968476650014054]
num = 32
mul [0.03118283900039387, 0.03388790600001812, 0.03745272100059083]
pow [0.0943321790000482, 0.09484523300125147, 0.09691544299857924]
num = 64
mul [0.030481540998152923, 0.03292956899895216, 0.03887743200175464]
pow [0.09454960600123741, 0.09569520199875114, 0.09926063899911242]
num = 128
mul [0.030935312999645248, 0.031198748001770582, 0.03733277300125337]
pow [0.09531564099961543, 0.09669112700066762, 0.09679062199938926]
num = 256
mul [0.03280377900227904, 0.03324341500047012, 0.04479783699935069]
pow [0.09439349899912486, 0.09439918999851216, 0.09548852000079933]
num = 512
mul [0.03275527599907946, 0.03428718699797173, 0.038492286003020126]
pow [0.10492119499758701, 0.10698100599984173, 0.13057717199990293]
2 of 4
4

You should wrap the expression into [] in order to have a list comprehension.

print([i**2 for i in range(int(input()))])

If you want to print the results line by line just use extended iterable unpacking operator.

print(*[i**2 for i in range(int(input()))], sep = '\n')
🌐
Python.org
discuss.python.org › python help
Changing output to only one line - Python Help - Discussions on Python.org
March 28, 2022 - Hello, I’m still a beginner to Python coding. Currently, I’m stuck at this part where I’m trying to generate ONLY one line of output that contains the answers. Instead of repeating the ‘Vowels are:’ output, I want my output to just be: Vowels are: [ans1] [ans2] … Also, my side question is how can i opt out the same answer, like in this case with 4 u’s? Here’s my code: yourSentence = input(“Enter your sentence here:”).lower() numberofVowels = set(‘aeiou’) number=set(‘0123456789’) count...
🌐
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 ...
🌐
sebhastian
sebhastian.com › python-one-line-for-loop
Python one line for loop tutorial | sebhastian
February 22, 2023 - Suppose you want to add a +2 to a range of numbers from 1 to 5. Here’s how you do it using a regular for loop: result = [] for i in range(1, 6): result.append(i + 2) print(result) # [3, 4, 5, 6, 7] You can shorten the code above by using a list comprehension as follows: result = [i + 2 for i in range(1, 6)] print(result) # [3, 4, 5, 6, 7] Isn’t that simple? List comprehension allows you to create a list and do operations on the list items in one line.