72

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
seiryuu10
  • 843
  • 1
  • 10
  • 14

15 Answers15

108
def altElement(a):
    return a[::2]
Muhammad Alkarouri
  • 23,884
  • 19
  • 66
  • 101
99

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

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
Darius Bacon
  • 14,921
  • 5
  • 53
  • 53
32

Alternatively, you could do:

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

The extended slice notation is much more concise, though.

Joel Cornett
  • 24,192
  • 9
  • 66
  • 88
  • 2
    This was helpful for me, but it's different from the extended slice notation in that it gives you an index with which you can then reach into the original array, instead of getting a "filtered" array. So they do have different use cases. – Daniel F Dec 11 '15 at 11:43
  • 1
    The biggest advantage of this answer is that it's much more readable than "extended slice notation", especially by non-python devs. – Johan Jan 11 '21 at 10:03
11
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]
]
jdi
  • 90,542
  • 19
  • 167
  • 203
  • 1
    The only answer to solve the sister problem: every-other-element has two interpretations. – Bob Stein Feb 24 '19 at 18:50
  • @jdi Instead of `[1::2]`; What if I want every "other element" starting from `index = 0`? So `[0, 2, 4, 6, 8]`. Thanks. –  Aug 04 '21 at 09:40
  • 1
    @StressedBoi_69420 the syntax is `[start:end:step]` so just change it to `[0::2]` to have it start at 0 instead of 1 – jdi Aug 05 '21 at 19:44
7

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]
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
4
b = a[::2]

This uses the extended slice syntax.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
1

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

  • Please provide some description for your code, for further detail – Farbod Ahmadian Jun 16 '20 at 19:46
  • I ran into this problem in coursera's "Crash course on python"; I don't like the hints(comments) offered by the course, like other answer mentioned, we could iterate using "2" as step in range() to skip elements, I don't understand why they ask to implement with nested loops and variable "words" are not used here. – zeal4learning Feb 16 '21 at 22:39
1
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
Gaya3
  • 11
  • 2
1
# 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
0
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.

0
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([]))
Palo
  • 974
  • 12
  • 27
0
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
Amarth Gûl
  • 1,040
  • 2
  • 14
  • 33
ree_d_wan
  • 11
  • 1
0

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.

bchurchill
  • 1,410
  • 8
  • 23
  • Why aren't you simply using a boolean as the toggle? Also, this is unspeakably unidiomatic. – Niklas B. Jan 14 '12 at 22:35
  • 1
    I wrote it this way to mirror the author's attempt. Yes, it's not very python like. Sure, I'll happily edit and make it a bool... – bchurchill Jan 14 '12 at 22:36
  • this is a really poor approach considering you can use list slices – jdi Jan 14 '12 at 22:37
  • 2
    @bchurchill - I dont think the idea was to mirror exactly what the author was attempting. He stated he wasnt even sure the right way to do it at all. It would be a lot better to point him towards the idiomatic way of doing it in python – jdi Jan 14 '12 at 22:38
-1
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']))  
Shan S
  • 658
  • 5
  • 18
TE A 24
  • 13
  • 4
  • 1
    TE A 24, I doubt that this helps, or even works at all. To convince me otherwise please add an explanation of how this works and why it is suppoed to help. – Yunnosch Jul 18 '20 at 10:24
  • Ok........I first create new list ....In the for loop we enumerate because we have to play with the index number that means odd or even...then if condition apply ....if index is divisible by 2 then we have to append or add it...... – TE A 24 Jul 19 '20 at 12:53
-2
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 []
zx485
  • 28,498
  • 28
  • 50
  • 59