[Tutor] function call inside generator expression

Manprit Singh manpritsinghece at gmail.com
Tue Oct 20 01:15:06 EDT 2020


Dear sir ,

Consider an example where I have to print  only those items from the old
existing list whose sum of digits is equals or greater than 13. The code is
given below:

def sum_digit(x):
      m = x
      tot = 0
      while m != 0:
          m, r = divmod(m, 10)
          tot = tot + r
      return tot


l = [23, 47, 42,
     98, 65, 91,
     66, 58, 21,
     49, 34, 69]

lst_flt = (i for i in l if sum_digit(i) >= 13)
print(*lst_flt)

The output is :

98 58 49 69

Which is the right answer. So as you can see i have used sum_digit(i) >= 13

inside the generator expression, which is a function call. It is ok to use

function calls inside generator expressions and comprehensions in the way as

given above .

I have one more question. If you can see the function definition, you can

found that i have done m = x, reason for doing this is actually i do not

have the habit to modify the formal parameter of the function definition.

Now here x is immutable , modifying m  inside definition will not have
any effect on x. If the function was made to accept a list, i would have

made a shallow copy of list by doing y = x[:] and then have performed any

action on y to get the result so that the list passed to formal parameter

does not get affected. Need your sincere suggestion on this point.


Secondarily if there is any other efficient way to implement it ?

Regards

Manprit Singh


More information about the Tutor mailing list