Extract Elements of List at Odd Positions

Extract elements of list at odd positions

Solution

Yes, you can:

l = L[1::2]

And this is all. The result will contain the elements placed on the following positions (0-based, so first element is at position 0, second at 1 etc.):

1, 3, 5

so the result (actual numbers) will be:

2, 4, 6

Explanation

The [1::2] at the end is just a notation for list slicing. Usually it is in the following form:

some_list[start:stop:step]

If we omitted start, the default (0) would be used. So the first element (at position 0, because the indexes are 0-based) would be selected. In this case the second element will be selected.

Because the second element is omitted, the default is being used (the end of the list). So the list is being iterated from the second element to the end.

We also provided third argument (step) which is 2. Which means that one element will be selected, the next will be skipped, and so on...

So, to sum up, in this case [1::2] means:

  1. take the second element (which, by the way, is an odd element, if you judge from the index),
  2. skip one element (because we have step=2, so we are skipping one, as a contrary to step=1 which is default),
  3. take the next element,
  4. Repeat steps 2.-3. until the end of the list is reached,

EDIT: @PreetKukreti gave a link for another explanation on Python's list slicing notation. See here: Explain Python's slice notation

Extras - replacing counter with enumerate()

In your code, you explicitly create and increase the counter. In Python this is not necessary, as you can enumerate through some iterable using enumerate():

for count, i in enumerate(L):
if count % 2 == 1:
l.append(i)

The above serves exactly the same purpose as the code you were using:

count = 0
for i in L:
if count % 2 == 1:
l.append(i)
count += 1

More on emulating for loops with counter in Python: Accessing the index in Python 'for' loops

Remove odd-indexed elements from list in Python

You can delete all odd items in one go using a slice:

del lst[1::2]

Demo:

>>> lst = ['712490959', '2', '623726061', '2', '552157404', '2', '1285252944', '2', '1130181076', '2', '552157404', '3', '545600725', '0']
>>> del lst[1::2]
>>> lst
['712490959', '623726061', '552157404', '1285252944', '1130181076', '552157404', '545600725']

You cannot delete elements from a list while you iterate over it, because the list iterator doesn't adjust as you delete items. See Loop "Forgets" to Remove Some Items what happens when you try.

An alternative would be to build a new list object to replace the old, using a list comprehension with enumerate() providing the indices:

lst = [v for i, v in enumerate(lst) if i % 2 == 0]

This keeps the even elements, rather than remove the odd elements.

Split a list into half by even and odd indexes?

This should give you what you need - sampling a list at regular intervals from an offset 0 or 1:

>>> a = ['blah', 3,'haha', 2, 'pointer', 1, 'poop', 'fire']
>>> a[0:][::2] # even
['blah', 'haha', 'pointer', 'poop']
>>> a[1:][::2] # odd
[3, 2, 1, 'fire']

Note that in the examples above, the first slice operation (a[1:]) demonstrates the selection of all elements from desired start index, whereas the second slice operation (a[::2]) demonstrates how to select every other item in the list.

A more idiomatic and efficient slice operation combines the two into one, namely a[::2] (0 can be omitted) and a[1::2], which avoids the unnecessary list copy and should be used in production code, as others have pointed out in the comments.

How to extract every odd numbered element in list

this should solve your problem:

my_list[seq(1, length(my_list), 2)]

i would advise you against using inbuilt R functions as names for your objects (ls). also look up some elementary R list manipulations, indexing, etc

How to get the oddly indexed elements in a list in mathematica

There are a lot of ways, here are some of them:

In[2]:= a = Range[10];le = Length@a;

In[3]:= Table[a[[i]], {i, 1, le, 2}]

In[5]:= Pick[a, Table[Mod[i, 2], {i, 1, le}], 1]

In[6]:= a[[1 ;; le ;; 2]]

In general, with Pick[] (as an example) you can model any conceivable index mask.

Shortest way to slice even/odd lines from a python array?

Assuming you are talking about a list, you specify the step in the slice (and start index). The syntax is list[start:end:step].

You probably know the normal list access to get an item, e.g. l[2] to get the third item. Giving two numbers and a colon in between, you can specify a range that you want to get from the list. The return value is another list. E.g. l[2:5] gives you the third to sixth item. You can also pass an optional third number, which specifies the step size. The default step size is one, which just means take every item (between start and end index).

Example:

>>> l = range(10)
>>> l[::2] # even - start at the beginning at take every second item
[0, 2, 4, 6, 8]
>>> l[1::2] # odd - start at second item and take every second item
[1, 3, 5, 7, 9]

See lists in the Python tutorial.

If you want to get every n-th element of a list (i.e. excluding the first element), you would have to slice like l[(n-1)::n].

Example:

>>> l = range(20)
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

Now, getting every third element would be:

>>> l[2::3]
[2, 5, 8, 11, 14, 17]

If you want to include the first element, you just do l[::n].

How to print the elements in odd positions in a list using an iterative function in Lisp?

The easiest way is to reverse the result:

(defun pozpar (lst)
(do ((l lst (cddr l))
(x '() (cons (car l) x)))
((null l)
(nreverse x))))

(pozpar '(1 2 3 4 5))
==> (1 3 5)

Notes

  1. This returns, not outputs the value you want.

  2. Prepending values and reverting the result is a common Lisp coding pattern.

  3. Since append is linear in the length of its argument, using it in a loop produces quadratic code.

  4. I formatted the code in the standard Lisp way. If you use this style, lispers will have an easier time reading your code, and, consequently, more willing to help you.



Related Topics



Leave a reply



Submit