I have the general idea of how to do this in Java, but I am learning Python and not sure how to do it.
I need to implement a function that returns a list containing
Or you can do it like this!
def skip_elements(elements):
# Initialize variables
new_list = []
i = 0
# Iterate through the list
for words in elements:
# Does this element belong in the resulting list?
if i <= len(elements):
# Add this element to the resulting list
new_list.append(elements[i])
# Increment i
i += 2
return new_list
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']
print(skip_elements([])) # Should be []
items = range(10)
print items
>>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print items[1::2] # every other item after the second; slight variation
>>> [1, 3, 5, 7, 9]
]
Slice notation a[start_index:end_index:step]
return a[::2]
where start_index
defaults to 0
and end_index
defaults to the len(a)
.
def skip_elements(elements):
# Initialize variables
new_list = []
i = 0
# Iterate through the list
for words in elements:
# Does this element belong in the resulting list?
if i <= len(elements):
# Add this element to the resulting list
new_list.insert(i,elements[i])
# Increment i
i += 2
return new_list
There are more ways than one to skin a cat. - Seba Smith
arr = list(range(10)) # Range from 0-9
# List comprehension: Range with conditional
print [arr[index] for index in range(len(arr)) if index % 2 == 0]
# List comprehension: Range with step
print [arr[index] for index in range(0, len(arr), 2)]
# List comprehension: Enumerate with conditional
print [item for index, item in enumerate(arr) if index % 2 == 0]
# List filter: Index in range
print filter(lambda index: index % 2 == 0, range(len(arr)))
# Extended slice
print arr[::2]
b = a[::2]
This uses the extended slice syntax.