0

I need to make a list comprehension to create a list of squared numbers. The function has the parameters start and end, and I want it to returns a list of squares of consecutive numbers between start and end inclusively.

I've tried various ways to solve this problem, but I've failed. I have also removed my code, that I wrote in attempts to solve the question.

def squares(start, end):
    return [  ]

print(squares(2, 3)) # Should output [4, 9]
print(squares(1, 5)) # Should output [1, 4, 9, 16, 25]
print(squares(0, 10)) # Should output [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
halfer
  • 19,824
  • 17
  • 99
  • 186
  • 1
    Does this answer your question? [How to use a list comprehension to square numbers from start to end?](https://stackoverflow.com/questions/61866543/how-to-use-a-list-comprehension-to-square-numbers-from-start-to-end) – Gino Mempin Dec 15 '20 at 00:22
  • That's useful, haha; but this question was posted over 7 months ago; and was answered previously; a long time ago. Although thank you for referring the other answer. – Human Being Dec 16 '20 at 15:31
  • That was actually not meant to ask for your response (yeah, the wording is weird). It is an auto-posted auto-comment when flagging a question as a duplicate of another question. – Gino Mempin Dec 17 '20 at 00:36
  • ahh alright was confused about that – Human Being Dec 18 '20 at 02:42

3 Answers3

2

You can do it the following way

def squares(start, end):
    if start > end:
        raise ValueError("start should be less or equal to end")
    return [num**2 for num in range(start, end+1)]
vkozyrev
  • 1,770
  • 13
  • 13
0

You can use this:

def squares(start, end):
    lst = []
    for num in range(start, end+1):
        num = num**2
        lst.append(num)
    return lst

print(squares(2, 3)) # Should output [4, 9]
print(squares(1, 5)) # Should output [1, 4, 9, 16, 25]
print(squares(0, 10)) # Should output [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

I have tried and it works. Also, you can check this question.

CoderCat
  • 22
  • 4
  • I originally wasn't going to give it to you, since you were not the first answer, but since you're a new contributor I'll do so! – Human Being Apr 21 '20 at 16:45
  • Ah thanks a lot! It was necessary to be able to comment, that's why I asked, thank you. – CoderCat Apr 21 '20 at 16:48
0
def squares(start, end):
    result = []
    for  i in range(start,end+1):
        result.append(i**2)
    return result
kaungmyathan
  • 11
  • 1
  • 2