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!

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

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

Something like:

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

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!

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

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)))
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.