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)?

3
  • What if a number is divisible by more than one of those? Commented Apr 30, 2016 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). Commented Apr 30, 2016 at 10:17
  • don't use list name; it overshadows the builtin list. Commented Apr 30, 2016 at 10:41

4 Answers 4

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]
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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 ..

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.