Home > other >  Python how to put function or method in array while only being called once referenced
Python how to put function or method in array while only being called once referenced

Time:06-07

If i have this tuple:

tuple = (a   1,'hello','hello2',etc...)

and at the start of the program, variable a is 1, while being 2 later on, tuple[0] sould return 2 at the start, and 3 at the end. how do i go about doing this?

should i make it 'a 1' and use eval()? don't ask "why i would need this" or "why am i doing it this way" because we all know the 'uninformative people on stackoverflow' memes, and i genuinely need to know.

CodePudding user response:

Use a function.

a = 1
my_tuple = (lambda x: x   1, "hello")
a = my_tuple[0](a)
print(a) # prints 2
a = my_tuple[0](a)
print(a) # prints 3

CodePudding user response:

To compliment what @Barmar has posted you could do something like the following using eval.

a = 1
my_tuple = (lambda: eval('a   1'), "hello")
print(my_tuple[0]()) # prints 2
a = 2
print(my_tuple[0]()) # prints 3
  • Related