1.11M Members

Squaring each number in a list

 
0
 

I am trying to square each number in the list under nums. But I don't know how to do it. I got this so far:

def squareEach(nums):
	for i in nums:
		y=i*i
	return y

What is happening here is it's counting how many numbers are in the list and then squaring it.I want the square of each number in the list....please help!thanks!

 
0
 
def squareEach(nums):
    return [i*i for i in nums]
 
0
 

Thanks!:) But what if it's in the arrangement like mine, how would you write that with the same output as yours?

 
0
 

Something like:

def squareEach(nums):
    squares=[]
    for number in nums:
        squares.append(number*number)
    return squares
 
0
 

what if <list>.append(x) is not used, is there any other way to write this code in that arrangement? I'm sorry...I'm new to this and I haven't learned that yet..well now i have but I can't use that yet. thanks!

Question Answered as of 4 Years Ago by pyTony
 
0
 
def squareEach(nums):
    squares=[]
    for number in nums:
        squares += [number * number]
    return squares
 
0
 

what if <list>.append(x) is not used, is there any other way to write this code in that arrangement? I'm sorry...I'm new to this and I haven't learned that yet..well now i have but I can't use that yet. thanks!

You could print them out instead of returning the value or build the result with +, which is not the recommended way. Or you could use recursion.

def squareEach(nums):
    squares=[]
    for number in nums:
        squares+=[number*number]
    return squares

# test it
print zip(range(20),squareEach(range(20)))
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article