Reputation: 109
Say I have a function called everythird that takes a list as its parameter and returns a new list containing every third element of the original list, starting from index 0. I know how to do this using slice notation (return everythird[0::3]), but we have to use a while loop only. If I type in everythird([1, 2, 3, 4, 5, 6, 7, 8]), I want it to return [1, 4, 7]. I tried a few different ways, but I'm not getting a list back, or I only get one value back. How do I return a list? Also how do you know for certain whether something modifies or doesn't modify an original list?
Thank you.
This is one of the ways I attempted this: every_third([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
def everythird(l):
'''(list) -> list
Returns every third element of original list, starting at index 0'''
i = 0
while i < len(l):
print(l[i])
i += 3
This prints
1
4
7
Upvotes: 1
Views: 3024
Reputation: 78620
If you need to do this with a while loop, you could do it by appending each element to a list rather than printing it, and then returning that list:
def everythird(l):
i = 0
ret = []
while i < len(l):
ret.append(l[i])
i += 3
return ret
Though as you note, it would certainly be preferably to do
def everythird(l):
return l[0::3]
Or if you were allowed to use a for
loop:
def everythird(l):
ret = []
for i in range(0, len(l), 3):
ret.append(l[i])
return ret
Finally, if you were allowed to use a list comprehension:
def everythird(l):
return [l[i] for i in range(0, len(l), 3)]
The slice indexing is certainly the best, but in any case a while loop might be the worst way to do it.
Upvotes: 5