Search code examples
pythonperfect-square

Counting and generating perfect squares


I need some advice on how to write a Python program where it gives you a list of the first n perfect squares in list format. The output should look like this:

How many squares?: 5  
[1, 4, 9, 16, 25]

This is what I have so far:

n = int(raw_input("How many squares? "))

Now for the next part I need to create a list of the first n squares. Any suggestions on how? Thank you for your time and advice.


Solution

  • Use a list comprehension:

    [ a*a for a in xrange(1, n + 1) ]