0

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']

4
  • I have the following code but I get an error Saying "I got an error" isn't very useful. Show us the error. Commented Nov 19, 2020 at 0:51
  • li.remove(a) What is li? You haven't defined that variable. Commented Nov 19, 2020 at 0:51
  • Forgive me @JohnGordon it meant to say List but an answer has been supplied already. Thank you Commented Nov 19, 2020 at 0:53
  • 1
    I'm guessing the error was TypeError: unsupported operand type(s) for %: 'list' and 'int' since you are trying to apply % to something between brackets! Commented Nov 19, 2020 at 1:00

3 Answers 3

3

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Can you you kindly help me understand ` [str(z) for z in range(1,10,2)]`?
That is a list comprehension to iterate over the range of 1 to 11 with step 2 and convert each iteratiom variable to str and compare
In the event that I need to change the condition from ``Odd` to a list of numbers for example [6,7,8,9] am I correct to write [str(z) for z in range(6,8,1)]?
1

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']

Comments

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

2 Comments

This actually has quadratic time complexity because remove has to search for the element before removing it.
Suggested alternative: newlist = []; for a in List: if a[-2] in '13579': newlist.append(a).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.