Skipping every other element after the first
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 every other element of the list, starting with the first element.
Thus far, I have and not sure how to do from here since I am just learning how for-loops in Python are different:
def altElement(a):
b = []
for i in a:
b.append(a)
print b
def altElement(a):
return a[::2]
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)
.
Alternatively, you could do:
for i in range(0, len(a), 2):
#do something
The extended slice notation is much more concise, though.
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]
]
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]