2

For example, the following code:

list1 = [23, 3, 6, 5, 12, 9, 7, 4]
remove_even_list(list1)
print(list1)

prints

[23, 3, 5, 9, 7]

Here is what I coded:

def remove_even_list(numbers):
    for index in range(len(numbers)-1,-1,-1):
        if numbers[index] % 2 == 0:
            numbers.pop[index]

def test_remove_even_list():    
    list1 = [23, 3, 6, 5, 12, 9, 7, 4]
    remove_even_list(list1)
    print(list1)

It can run, but run nothing. Please help me to figure out the mistakes as above. Many thanks.

user2390182
  • 72,016
  • 6
  • 67
  • 89
Christina
  • 29
  • 1
  • 2
  • 1
    what do you mean by "it can run, but run nothing"? – dangee1705 Sep 20 '18 at 11:23
  • Possible duplicate of [How do I remove an element from a list by index in Python?](https://stackoverflow.com/questions/627435/how-do-i-remove-an-element-from-a-list-by-index-in-python) – Sheldore Sep 20 '18 at 11:24
  • Just in case you are interested, `reverse` is pretty for iterating through lists. For example `for index, element in enumerate(reversed(numbers))` `if element % 2 == 0:` `numbers.pop(index)` – Guimoute Sep 20 '18 at 12:17
  • Running the code I get the message `TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'`. I understand that you didn't get the output that you wanted, and I also understand that the error message was hard for you to understand. But reporting the error message is important, even if you don't understand it, because it helps us help you. – BoarGules Sep 20 '18 at 12:53

2 Answers2

4

You have just made a simple error

numbers.pop[index]

should be

numbers.pop(index)
dangee1705
  • 3,445
  • 1
  • 21
  • 40
1

Your question was not exactly about it, but this filter the even numbers without loop.

list1 = [23, 3, 6, 5, 12, 9, 7, 4]    
print(list(filter(lambda x: x % 2, list1)))

or

list1 = [23, 3, 6, 5, 12, 9, 7, 4]
print([x for x in list1 if(x % 2 !=0)])

or

list1 = [23, 3, 6, 5, 12, 9, 7, 4]
print([x for x in list1 if x % 2])
tkircsi
  • 315
  • 3
  • 14