Moshe
Moshe

Reputation: 117

Pandas Python remove elements from list with condition

Suppose I have a the following list

List = ['0000', '0010', '0020', '0030', '0040', '0050', '0060', '0070']
Using Pandas python I want to remove elements from list where the 2nd last numbers is odd. I have the following code but I get an error.

for a in List:
    if [int(a[-2]) for a in List] % 2 != 0:
        List.remove(a)

Expected Output List = ['0000', '0020', '0040', '0060']

Upvotes: 0

Views: 281

Answers (3)

BENY
BENY

Reputation: 323226

Since you tagged the question pandas:

out = pd.Series(List).loc[lambda x : x.str[-2].astype(int)%2==0].tolist()
Out[94]: ['0000', '0020', '0040', '0060']

Upvotes: 1

user27637
user27637

Reputation: 1

for a in List:
    if int(a[-2]) % 2 != 0:
        List.remove(a)

Upvotes: 0

wasif
wasif

Reputation: 15478

You are removing items from list while iterating, maybe that's the root of the problem, Try out a list comprehension

List = ['0000', '0010', '0020', '0030', '0040', '0050', '0060', '0070']

List = [x for x in List if not x[-2] in [str(z) for z in range(1,10,2)]]

print(List)

Upvotes: 3

Related Questions