0

I am trying to write an if statement in Python 3:

if n % 2 == 0:
    list.append(2)
elif n % 3 == 0:
    list.append(3)
elif n % 5 == 0:
    list.append(5)

Is there a more space conservative way of doing this? I thought about using lambda expressions, but these bits of code don't seem to work.

if (lambda i: n % i == 0)(i in [2,3,5])
    list.append(i)

and

if (lambda i: n % i == 0)([2,3,5])
    list.append(i)

Is there a way to do this using lambda expressions? Or do I need a different approach? Also, if I use lambda expressions, will I be able to use the value of i for which the condition matches (like appending it to a list)?

Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
ratorx
  • 257
  • 1
  • 8
  • What if a number is divisible by more than one of those? – tobias_k Apr 30 '16 at 10:17
  • I recommend that you first try it with traditional functions and then, once you're comfortable with that, transforming them into `lambda` one-liners (which isn't actually necessary anyway). – TigerhawkT3 Apr 30 '16 at 10:17
  • don't use `list` name; it overshadows the builtin `list`. – jfs Apr 30 '16 at 10:41

4 Answers4

2
>>> n = 33
>>> [i for i in (2, 3, 5) if n % i == 0]
[3]
>>> n = 10
>>> [i for i in (2, 3, 5) if n % i == 0]
[2, 5]
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
1

To get the same result as if/elif/elif statements in the question:

your_list += next(([d] for d in [2, 3, 5] if n % d == 0), [])  

Note: only the first divisor is appended to the list. See find first element in a sequence that matches a predicate.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670
0

I can't do it with lambda functions but I think this approach with help u

list = [1,2,3] 
n = 9
[list.append(i) for i in (2,3,5) if n % i == 0]
print list
[1, 2, 3, 3]

and so on ..

niemmi
  • 17,113
  • 7
  • 35
  • 42
0

Like J.F. Sebastian`s answer this gives only the first divisor:

res_list.extend([i for i in (2, 3, 5) if n % i == 0][:1])

The [:1] takes only the first element of the list and gives an empty list if the list is empty (because a slice of an empty list is always an empty list).

Now, extend() adds a one-element list as a single element to your result list or nothing for a zero-element list.

Mike Müller
  • 82,630
  • 20
  • 166
  • 161