Squares
Four ways to take a list of integers and return a list containing the square of each number in the list.
####Method 1: A while loop
def squares1(list):
result = []
i = 0
length = len(list)
while i < length:
result.append(list[i] ** 2)
i = i + 1
return result
A while
loop will keep going until the expression i < len(list)
returns false. A counter i
is required to keep track of where you are in the list.
####Method 2: A for loop
def squares2(list):
result = []
for i in list:
result.append(i ** 2)
return result
A for
loop can be used to iterate over each element in a list (or a string). The loop will automatically come to an end after each element in the list has been visited. There is no need for any variables to act as a counter.
####Method 3: A list comprehension
def squares3(list):
return [ i ** 2 for i in list ]
List comprehensions are very nice. Get familiar with them and use them where you can.
####Method 4: pop the list until it is empty
def squares4(list):
result = []
while list:
result.append(list.pop() ** 2)
return result.reverse()
Empty sequences (lists, strings) are considered false, so testing a list while repeatedly pop()
ing it will successfully cause the loop to come to an end when there are no elements left to pop. The result needs to be reversed, because elements are popped from the end of a list by default. pop(0)
would cause elements to be removed from the front of the list instead.
This function has the side effect of emptying out the original list passed in as an argument, which may not be what you want.