rh1990
rh1990

Reputation: 940

Conditionally delete an element from an array

I'd like to conditionally delete an element from an array of arbitrary length, e.g.

list = [1, 2, 3, 4, 3, 2, 1]
condition = 3

for i in range(len(list)):
    if list[i] >= condition:
        list.pop(i)

Would result in

list = [1, 2, 2, 1]

Is there a more 'pythonic' way of doing this, such as list comprehension?

Thandel

Upvotes: 1

Views: 137

Answers (3)

Trolldejo
Trolldejo

Reputation: 466

Here you go, using list comprehension:

list = [1, 2, 3, 4, 3, 2, 1]
condition = 3
newlist = [x for x in list if x < condition]

Upvotes: 1

Christoph Engwer
Christoph Engwer

Reputation: 821

Do you have to stick to the list datatype? Have you thought of using numpy arrays? A pythonic way with numpy would look something like this:

import numpy as np
arr = np.array([1, 2, 3, 4, 3, 2, 1])
condition = 3

conditioned_arr = arr[arr < condition]

>>> print(conditioned_arr)
array([1, 2, 2, 1])

Upvotes: 0

e4c5
e4c5

Reputation: 53734

If you want the original list to be modified, you would need something like what you are doing. if you want a new list the following one liner works

[i for i in llist if i < 3]

Please note that I have renamed your variable as llist since list is a built in.

Upvotes: 4

Related Questions