1,105,644 Community Members

Squaring each number in a list

Member Avatar
abcdr
Newbie Poster
6 posts since Jul 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
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!

Member Avatar
pyTony
pyMod
6,104 posts since Apr 2010
Reputation Points: 818 [?]
Q&As Helped to Solve: 1,056 [?]
Skill Endorsements: 42 [?]
Moderator
Featured
 
0
 
def squareEach(nums):
    return [i*i for i in nums]
Member Avatar
abcdr
Newbie Poster
6 posts since Jul 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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

Member Avatar
pyTony
pyMod
6,104 posts since Apr 2010
Reputation Points: 818 [?]
Q&As Helped to Solve: 1,056 [?]
Skill Endorsements: 42 [?]
Moderator
Featured
 
0
 

Something like:

def squareEach(nums):
    squares=[]
    for number in nums:
        squares.append(number*number)
    return squares
Member Avatar
abcdr
Newbie Poster
6 posts since Jul 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
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 3 Years Ago by pyTony
Member Avatar
Beat_Slayer
Posting Pro in Training
401 posts since Jun 2010
Reputation Points: 17 [?]
Q&As Helped to Solve: 105 [?]
Skill Endorsements: 1 [?]
 
0
 
def squareEach(nums):
    squares=[]
    for number in nums:
        squares += [number * number]
    return squares
Member Avatar
pyTony
pyMod
6,104 posts since Apr 2010
Reputation Points: 818 [?]
Q&As Helped to Solve: 1,056 [?]
Skill Endorsements: 42 [?]
Moderator
Featured
 
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