0

The task is to create modify_list(l) function, which removes odd numbers from the list and divides even numbers in the list by 2 without remainder.

#My code
lst = [1, 2, 3, 4, 5, 6]
def modify_list(l):
  for k in l:
    if k%2 == 1:
      l.remove(k)
    elif k%2 != 1:
      l.remove(k)
      l.append(k//2)
  return l
print(modify_list(lst))


#This is how function is expected to work:
lst = [1, 2, 3, 4, 5, 6]
print(modify_list(lst))  # None
print(lst)               # [1, 2, 3]
modify_list(lst)
print(lst)               # [1]
#My code returns:
print(modify_list(lst))   #[2, 4, 6] instead of none or at least [1, 2, 3]

So, elif part of code is just ignored! I dont't understand why

alyssad
  • 15
  • 4
  • You are modifying the list you are iterating on, instead iterate on a copy of list `l[:]` – Devesh Kumar Singh Jun 15 '19 at 10:56
  • @DeveshKumarSingh Why do we have to copy a list ? The task is to modify a list, not to create a new one. Lists are mutable objects, arent they? – alyssad Jun 15 '19 at 11:34
  • if you modify the same list you are iterating on, you will get the issue you just saw, so you need to `iterate` on the copy of list by `for k in l[:]:`, check the duplicate and it will make sense to you – Devesh Kumar Singh Jun 15 '19 at 11:36

1 Answers1

0

You need to create a copy of the list. However, the following syntax should give you the desired outcome and is more readable:

def modify_list(l):
    return [value // 2 for value in l if value % 2 == 0]

You are basically creating a new list using list comprehension that contains halved the values which are evens.

Rafael
  • 7,002
  • 5
  • 43
  • 52