- Practice
- Python
- Introduction
- Loops
- Discussions

# Loops

# Loops

tarathedev + 28 comments Thought my solution turned out looking pretty good so I thought I'd share:

print(*[num**2 for num in range(n)], sep='\n')

surfer2047 + 1 comment How does print(*[list]) works, could you please tell.

rpepato + 0 comments This is an arbitrary argument list. It works by expanding a list into a sequence of positional parameters by using the * operator. Take a look at this examples at the python tutorial.

nthomas1999 + 0 comments Beautiful. You taught me something today. Thanks

Canas + 9 comments Though I like your solution (great use of unpacking), I think this is just more straightforward

[print(i**2) for i in range(n)]

arpita0116 + 2 comments why the square bracket ?

Canas + 4 comments The square bracket in this case corresponds to a List Comprehension in Python. They're neat for many reasons, but for this particular case it's mostly a better looking (and probably faster) for-loop.

arpita0116 + 0 comments Got it. Thanks

maheswaradito + 1 comment youu using python 2 or 3

sanketsonu321 + 0 comments Python 3

sweaze + 0 comments Thanks for the explanation.

GiddyUp + 0 comments Thanks for the link, I just learned something new

shankarmurthy88 + 0 comments where is that square bracket?

chadwalt + 4 comments FROM THIS:

counter = 0; while counter < n : print (counter**2) counter = counter + 1

TO THIS:

[print(i**2) for i in range(n)]

Thanks alot for that link

Lukewardly + 1 comment I would have said, from this:

for i in range(n): print(i**2)

To the following code

kumarparth123 + 4 comments ME TOO GETTING ERROR PLEASE HELP

nick3499 + 2 comments [deleted]kumarparth123 + 0 comments its working thanks.

kumarparth123 + 0 comments one more doubt are last five topics waste in hacker rank python

nick3499 + 0 comments [deleted]namanbhoj99 + 1 comment # using python 3

n = int(input())

for i in range(0,n): print(i*i) i= i+1

pratik15045569 + 1 comment no need to write i=i+1 . otherwise its perfect.

debashishthakur9 + 0 comments yes exactly its perfect without that

imsd_14 + 0 comments This will Work

i =0;

`while i < n: print(i**2) i = i + 1`

rupeshjawadwar + 3 comments File "solution.py", line 4 [print(i**2) for i in range(n)] ^ SyntaxError: invalid syntax

Getting error please help

nikhilnsr1998 + 0 comments i hope you got it by now, but the square brackets are at the wrong position... here we are printing a list ------->(unpacking) list : i**2 for i in range(n) where i iterates over the provided range and i**2 is computed out Syntax:

a=[i**2 for i in range(N)] print(a)

or in one line: print([i**2 for i in range(N)])

thomasokonkwo91 + 2 comments if __name__ == '__main__': n = int(raw_input()) i=0 for i in range(n): print pow(i,2)

karan_katam16 + 0 comments why i=0?

ashishfrancis291 + 0 comments This is the only thing that helped me because the output was not required in the list format. Thankyou so much !

angel_garcia20 + 0 comments You are probably using Python 2 instead of old Python 2 :P

somya_r_panda + 0 comments Is this list comprehension??

angel_garcia20 + 0 comments Lol! We both figured the exact same answer!

meanagray + 1 comment How to integrate the constraint of n < 20 ?

Canas + 1 comment In this case the assumption is that input is between 1 and 20, so we don't expect any other input.

If you wanted to enforce the constraint, the code would be extended to this

[print(i**2) for i in range(n) if n in range(1, 21)]

mrsfdri + 0 comments How does this code work? What is the logic behind this code?

DahliaSR + 1 comment No it is not, this means, that

*print()*will be called n-times instead of once.Besides that you need to keep in mind that any function or method in python

**always**returns*None*unless it is told explicitly to return something else. In your solution, the list comprehension will return a list of length n, where each item is*None*.`>>> n = 5 >>> [print(i**2) for i in range(n)] 0 1 4 9 16 [None, None, None, None, None]`

h150303105219 + 0 comments how to get output for testcase 1 result

bryon_nicoson + 0 comments it is an elegant python 3 solution

yingning600 + 1 comment Could you please explain what (i**2) means?

chaitanya215 + 0 comments "**" means to the power of (exponential). here it means i * i

chaitanya215 + 0 comments but n is a integer right? what is meant by 'range(n)'

sahilmutha1999 + 0 comments actually it is giving error at 'p' letter of print by using ur trick

ujwalc3 + 0 comments How does "**2" help here?

adocto01 + 1 comment When testing with input 21 I get 21 lines of output which violates the constraints as it's supposed to limit N to between 1 and 20. I'm kind of confused because I'm not sure whether the Problem's constraints mean we're supposed to restrain inputs to that range in the program or if the end user of the program will restrain their inputs to that range.

b0kater + 0 comments This refers to the test cases that hackerrank will use to check your work. The constraints state "our test data will fit these constraints."

nick3499 + 0 comments [deleted][deleted] + 0 comments thanks you thaught me something new and usefull

ic3balandran + 3 comments The problem was about loops. If you show that to a beginner most likely they will not understand.

The solution with loops is just as short.

for i in range(0, n): print(i * i)

DahliaSR + 1 comment This approach, would fail!

The exponent has to be*2*and not*i*.chris_m_sullens + 0 comments That's not an exponent: i*i = i**2

namanbhoj99 + 0 comments buT it only prints 0 and n squared

vnsst123 + 0 comments Yes sir. I am a beginner and was searching for this kind of a one. Thank you

huanyu_liao + 0 comments it seems that py2 doesn't support this syntax

DahliaSR + 0 comments Replace the list comprehension by a generator expression and you got the most efficient and shortest solution.

Lehonti + 2 comments Nice solution! How about using iterators instead of arrays? It's more memory-efficient

print(*(num**2 for num in range(n)), sep='\n')

nikhilproject1 + 0 comments why did you use " sep='\n' ". codes works without it

arsh_suri + 0 comments and what about the start after print. why is that used

sunnyjagtap23_sj + 0 comments error.......

Ashish25 + 0 comments Thanks for teaching argument unpacking along with list comprehension.

twistagent + 0 comments hey thats pretty good

sfasu77 + 0 comments Awesome, blows my solution away lol

ram031197 + 0 comments Why * is used in print statement

m_balasubramani1 + 0 comments Nice bro.. helped me in another problem. You've used 'sep' as an argument to the print statement. Is it defined somewhere? Could you pls clarify?

maxmarinibastos + 0 comments How does 1<=N<=20 in your code?

amrut05 + 0 comments why haven't you considered the constraint 1<=N<=20?

nihapandey113 + 0 comments "ValueError: invalid literal for int() with base 10: '' I am getting this error even after using your solution in Python 3. Can u please let me know whats the issue here

cristinamais2 + 0 comments Omg, I tried so many times until seeing your solution. Thank you.

kalyan_prsd + 0 comments It seesm an in valid syntax. Please check!

deepakyadav880 + 0 comments [deleted]ranjithkjagadis1 + 0 comments Awesome dude...

17h51a04c1 + 0 comments what is sep ?

himalayanram_it + 0 comments Can you expalin in detail, how this works?

shtlshelake + 0 comments could you please explain this logic. I am bit confused for this.

sheecegardezi + 0 comments its nice to compress solution, I loved when I could chain overloaded operators esp in C++ :D Its strangely satisfying. Over the years I had to unlearn and relearn writting code and I would make a suggestion that always write code which is easy to read without the need langue or version specific overloading.

ElFernando + 3 comments This is my solution papus

n=int(input())

for i in range(n):

`print(i**2)`

karthikeyan1204 + 1 comment try for i in range(0,n):

ElFernando + 0 comments It's a same! range(0,n) that range(n):

KavinRanawella + 0 comments this is working right?

namansharma0206 + 0 comments N=int(input()) for i in range(N): print(i**2) This one works

pkhadka56 + 2 comments I don't know why test case 1 keeps on failing.

PRASHANTB1984 + 1 comment Do take a look at the successful submissions on the leaderboard!

eng_shomer + 0 comments how to know the successful submission

pkhadka56 + 0 comments okay

knock320 + 0 comments I don't understand the obective. What is the obective?

Sowbarani + 0 comments n = int(raw_input()) for i in range(0,n): print i*i

while compiling the above code its showing the IndentationError, Why its occuring ? Can any one help on this ?

**Sorry: IndentationError: expected an indented block (solution.py, line 3)**

MatheusMuriel + 0 comments for i in range(n): print(i * i)

_clfm_ + 1 comment ## Python 3 - clean & correct

Using a simple list comprehension, then unpacking the list to print. Let me know if you have any questions!

n = int(input()) squares = [x ** 2 for x in range(n)] print(*squares, sep="\n")

(From my HackerRank repo on GitHub.)

mananmalik1996 + 1 comment why do we use print(*squares, sep="\n") and not print(squares, sep="\n") what is the importance of that * ?

_clfm_ + 0 comments `squares`

is a list, so if you say`print(squares)`

, Python will print the list like`[0, 1, 4, 9, ... ]`

, with brackets and commas. There is only one item to print (the list), so`sep`

doesn't actually get printed at all, since there are no two items to "separate".`print(*squares, sep="\n")`

uses the "unpacking" operator`*`

to essentially pass the elements of the list`squares`

to`print()`

as individual variables. This is equivalent to calling`print(squares[0], squares[1], squares[2], ... , sep="\n")`

, but is obviously preferable syntax.This is just to match the output format the challenge expects. There are other ways to print the list in that format.

[deleted] + 0 comments In this problem constrain is specified which is 1<=n<=20. Should this be a part of code? and if yes then how?

jefinpaul1 + 0 comments This also works [print(pow(i,2)) for i in range(n)]

rajeshyadav18ye1 + 0 comments n=int(input("")) for i in range (n): print(i * i )

Sort 394 Discussions, By:

Please Login in order to post a comment