Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing alternate elements in a List<T>

What is the most efficient way to remove alternate (odd indexed or even indexed) elements in an List<T> without using a place holder list variable?

Also it would be appreciated if you could mention the cost with each of your answer.

I'm looking for an efficient way to do this

Thanks in advance

like image 325
abhilash Avatar asked Mar 07 '09 13:03

abhilash


People also ask

How do I remove an alternate element from a list in Python?

Fun fact: to remove all even (positioned) elements you can do: for x in lst: lst. remove(x) . To remove all odds do: iter_lst = iter(lst); next(iter_lst); for x in iter_lst: lst. remove(x) .

How to remove element in a list?

There are three ways in which you can Remove elements from List: Using the remove() method. Using the list object's pop() method. Using the del operator.

What method do you use to remove an item from a list t at a specific index?

RemoveAt (Int32) Method is used to remove the element at the specified index of the List<T>. Properties of List: It is different from the arrays.

How do I remove a list of numbers from a list in Python?

In Python, use list methods clear() , pop() , and remove() to remove items (elements) from a list. It is also possible to delete items using del statement by specifying a position or range with an index or slice.


2 Answers

If you call RemoveAt for every item you remove, you will be moving a lot of data. The most efficient is to move the items together that you want to keep, then remove the unused items at the end:

int pos = 0;
for (int i = 0; i < values.Count; i += 2, pos++) {
    values[pos] = values[i];
}
values.RemoveRange(pos, values.Count - pos);

Edit:
This method will process a list of a million ints in 15 ms. Using RemoveAt it will take over three minutes...

Edit2:
You could actually start with pos=1 and i=2 (or 3), as the first item doesn't have to be copied to itself. This makes the code a bit less obvious though.

like image 56
Guffa Avatar answered Sep 21 '22 06:09

Guffa


Just for consideration of a solution that creates a new list, with a list old you could do this:

var newList = old.Where((_, i) => i%2 != 0).ToList();

or, obviously

var newList = l.Where((_, i) => i%2 == 0).ToList();

depending which alternation you choose.

EDIT

The answer is quite a bit quicker. If you read something else here, it's because I measured on a weekend and weekend's brain is funny. :( The closure solution is about 40% quicker while the answer is app. 2 orders of magnitude faster. I suppose it will really depend how big your list becomes!

like image 31
flq Avatar answered Sep 23 '22 06:09

flq