Skipping every other element after the first

PythonFor LoopElements

Python Problem Overview


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

Python Solutions


Solution 1 - Python

def altElement(a):
    return a[::2]

Solution 2 - Python

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).

Solution 3 - Python

Alternatively, you could do:

for i in range(0, len(a), 2):
    #do something

The extended slice notation is much more concise, though.

Solution 4 - Python

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]
]

Solution 5 - Python

>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]

Solution 6 - Python

b = a[::2]

This uses the extended slice syntax.

Solution 7 - Python

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 []

Solution 8 - Python

def skip_elements(elements):
   new_list = [ ]
   i = 0
   for element in elements:
       if i%2==0:
         c=elements[i]
		 new_list.append(c)
       i+=1
  return new_list

Solution 9 - Python

# Initialize variables
new_list = []
i = 0
# Iterate through the list
for i in range(len(elements)):
	# Does this element belong in the resulting list?
	if i%2==0:
		# Add this element to the resulting list
		new_list.append(elements[i])
	# Increment i
	i +=2

return new_list

Solution 10 - Python

Using the for-loop like you have, one way is this:

def altElement(a):
    b = []
    j = False
    for i in a:
        j = not j
        if j:
            b.append(i)

    print b

j just keeps switching between 0 and 1 to keep track of when to append an element to b.

Solution 11 - Python

def skip_elements(elements):
  new_list = []
  for index,element in enumerate(elements):
    if index == 0:
      new_list.append(element)
    elif (index % 2) == 0: 
      new_list.append(element)
  return new_list

Also can use for loop + enumerate. elif (index % 2) == 0: ## Checking if number is even, not odd cause indexing starts from zero not 1.

Solution 12 - Python

def skip_elements(elements):
	# Initialize variables
	i = 0
	new_list=elements[::2]
	return new_list

# Should be ['a', 'c', 'e', 'g']:    
print(skip_elements(["a", "b", "c", "d", "e", "f", "g"]))
# Should be ['Orange', 'Strawberry', 'Peach']:
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) 
# Should be []:
print(skip_elements([]))

Solution 13 - Python

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

Solution 14 - Python

def skip_elements(elements):
    # code goes here
    new_list=[]
    for index,alpha in enumerate(elements):
        if index%2==0:
            new_list.append(alpha)
    return new_list


print(skip_elements(["a", "b", "c", "d", "e", "f", "g"]))  
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach']))  

Solution 15 - Python

def skip_elements(elements):
# Initialize variables
new_list = []
i = 0

# Iterate through the list
for i in range(0,len(elements),2):
	# Does this element belong in the resulting list?
	if len(elements) > 0:
		# Add this element to the resulting list
		new_list.append(elements[i])	    
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 []

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionseiryuu10View Question on Stackoverflow
Solution 1 - PythonMuhammad AlkarouriView Answer on Stackoverflow
Solution 2 - PythonDarius BaconView Answer on Stackoverflow
Solution 3 - PythonJoel CornettView Answer on Stackoverflow
Solution 4 - PythonjdiView Answer on Stackoverflow
Solution 5 - PythonMr. PolywhirlView Answer on Stackoverflow
Solution 6 - PythonJohn ZwinckView Answer on Stackoverflow
Solution 7 - PythonRifat HossainView Answer on Stackoverflow
Solution 8 - PythonGaya3View Answer on Stackoverflow
Solution 9 - PythonMohammad AsifView Answer on Stackoverflow
Solution 10 - PythonbchurchillView Answer on Stackoverflow
Solution 11 - PythonIevgen ChuchukaloView Answer on Stackoverflow
Solution 12 - PythonJyotsna JhaView Answer on Stackoverflow
Solution 13 - Pythonree_d_wanView Answer on Stackoverflow
Solution 14 - PythonTE A 24View Answer on Stackoverflow
Solution 15 - PythonMayank Raj VaidView Answer on Stackoverflow