Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove odd-indexed elements from list in Python

I'm trying to remove the odd-indexed elements from my list (where zero is considered even) but removing them this way won't work because it throws off the index values.

lst = ['712490959', '2', '623726061', '2', '552157404', '2', '1285252944', '2', '1130181076', '2', '552157404', '3', '545600725', '0']


def remove_odd_elements(lst):
    i=0
    for element in lst:
        if i % 2 == 0:
            pass
        else:
            lst.remove(element)
        i = i + 1

How can I iterate over my list and cleanly remove those odd-indexed elements?

like image 422
avereux Avatar asked Mar 05 '15 17:03

avereux


People also ask

How do you remove an element at an index from a list in Python?

You can use the pop() method to remove specific elements of a list. pop() method takes the index value as a parameter and removes the element at the specified index. Therefore, a[2] contains 3 and pop() removes and returns the same as output.

How do you return the odd indexed elements in a list?

Use list indexing to get elements of a list in odd positions. Use list indexing a_list[1::2] to return every other element of a_list , starting at index 1 .

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

Syntax of del:Passing the name of the list followed by the index or an index range after del will remove the items from the list in python.


2 Answers

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.

like image 147
Martijn Pieters Avatar answered Nov 01 '22 07:11

Martijn Pieters


Since you want to eliminate odd items and keep the even ones , you can use a filter as follows :

>>>filtered_lst=list(filter(lambda x : x % 2 ==0 , lst))

this approach has the overhead of creating a new list.

like image 31
jihed gasmi Avatar answered Nov 01 '22 07:11

jihed gasmi