1

I must create a function, that takes a matrix as an argument and uses list comprehension to divide each element of the list by 2 if it is an even number. So if the argument passed to the function was m = [[5, 4], [2, 3], [6, 7]] The function would return the matrix m2 = [[5, 2], [1, 3], [3, 7]]

I have tried the following:

m = [[5, 4], [2, 3], [6, 7]]
result = [num / 2 for num in m if num % 2 == 0]
print (result)

But I receive this error:

line 2, in <listcomp>
    result = [num / 2 for num in m if num % 2 == 0]
TypeError: unsupported operand type(s) for %: 'list' and 'int'
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172

1 Answers1

0

This is what you look for:

def divide_evens_elems_list(lst):
    for i in range(len(lst)):
        for j in range(len(lst[i])):
            if lst[i][j]%2==0:
                lst[i][j]//=2

    return lst

m = [[5, 4], [2, 3], [6, 7]]
print(divide_evens_elems_list(m))
Alchimie
  • 426
  • 4
  • 12
  • 1
    This doesn't use a list comprehension. Although, a list comprehension isn't really necessary. But more importantly, this modifies the argument in-place, which is generally an anti-pattern (sometimes you might want to for space efficiency sake, but usually it is bad and can lead to subtle bugs) – juanpa.arrivillaga May 17 '20 at 04:10
  • This is mono operation function , it's not necessary to keep the original list . – Alchimie May 17 '20 at 04:16
  • 1
    what? It *does* keep the original list. The **problem** is that it mutates the list that is passed in as an argument, which is typically considered bad. – juanpa.arrivillaga May 17 '20 at 04:19