Reputation: 85
Try out the enumerate function for yourself in this quick exercise. Complete the skip_elements()
function to return every other element from the list, this time using the enumerate()
function to check if an element is on an even position or an odd position.
def skip_elements(elements):
# code goes here
return ___
print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g']
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach']
My below solution is only returning "a" and "orange"
I guess that the for
loop is not working correctly? What am I missing?
def skip_elements(elements):
# code goes here
for i,alpha in enumerate(elements):
if i%2==0:
return alpha
Upvotes: 0
Views: 2105
Reputation: 149
You are using return, which exits the loop. If you just want to print you will want something like:
def skip_elements(elements):
# code goes here
for i,alpha in enumerate(elements):
if i%2==0:
print(alpha)
If you want to return a list:
def skip_elements(elements):
even_elements = []
for i,alpha in enumerate(elements):
if i%2==0:
even_elements.append(alpha)
return even_elements
Upvotes: 0
Reputation: 183
The for loop is working properly the problem is that you are doing a return.When we do a return the control comes out of the loop. If you want to return the elements you can store them in a list and then return
def skip_elements(elements):
# code goes here
elements = []
for i,alpha in enumerate(elements):
if i%2==0:
elements.append(alpha)
return elements
Upvotes: 2
Reputation: 142
Use the slice property of the a list [start:stop:step]
["a", "b", "c", "d", "e", "f", "g"][::2]
Upvotes: -1