1

I want generate RGB color with Lambda function. I have tried to do this code:

r = lambda: random.randint(0,255)
color=[r,r,r]

print(r)
color

Output:

<function <lambda> at 0x7f2aca8a7c20>
  
  [<function __main__.<lambda>>,
   <function __main__.<lambda>>,
   <function __main__.<lambda>>] 

I did not even get one number (r). Can anyone explain to me why this function is not good?


Update and Edit:

I realized that the lambda is a function that receives no value r() But how do you make the paint work in the same method and not permanently

If it is possible to convert a variable to a random number - that will not be in the function. That is, whenever a variable is available it will be different?

  • 4
    `color=[r(),r(),r()]` – luk2302 Jan 10 '22 at 21:49
  • 4
    You didn't _call_ the function... – jonrsharpe Jan 10 '22 at 21:50
  • 1
    Related: [Purpose of calling function without brackets python](/q/21785933/4518341), [What is the difference between calling function with parentheses and without in python?](/q/46001292/4518341) – wjandrea Jan 10 '22 at 22:07
  • I don't understand the edit. 1) `r()` is not void, it returns an `int`. 2) What do you mean by "paint"? 3) What do you mean by the last paragraph? Is that what you're trying to accomplish? Why? Beware of the [XY problem](https://meta.stackexchange.com/q/66377/343832). – wjandrea Jan 10 '22 at 22:19
  • My target is write "randcolor" and get every time another color – Aviran Marzouk Jan 10 '22 at 22:35
  • 1
    Related? [Call a function in repl without brackets](/q/68280186/4518341) or [Possible to call single-parameter Python function without using parentheses?](/q/2932887/4518341). Both cover IPython's `%autocall`, which might be what you want since it looks like you're using IPython. You would just need to write the function `randcolor`. – wjandrea Jan 10 '22 at 22:46

1 Answers1

3

The function is fine, but you never called it.

color = [r(), r(), r()]

If this syntax is not familiar to you, it's mentioned in the official tutorial.

By the way, avoid named lambdas, use a def instead.

def r():
    return random.randint(0, 255)
wjandrea
  • 28,235
  • 9
  • 60
  • 81