Python Forum
can you call a function from a list?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
can you call a function from a list?
#1
What i am trying to do:
create a inventory item that uses a function.
The code doesn't work but i will include it as it shows the function i am trying to call on as a list item.

def hall():
    inv=[]
    name=''
    name=input('enter name')
    print('you found an item')
    inv+=trophy(name)
    return name,inv

def show(inv):
        print(inv)

def trophy(name):
  sym='.'
  for i in range(1, len(name)+5, 1):
        print (sym, end="")
  print("\n.."+str(name)+"..")
  for i in range(1, len(name)+5, 1):
        print (sym, end="")

def main():
        name,inv=hall()
        show(inv)
        trophy(name)
main()
Reply
#2
What are you trying to do? Describe using terms you know and don't worry about translating to Python.
Reply
#3
(Nov-09-2020, 01:47 AM)deanhystad Wrote: What are you trying to do? Describe using terms you know and don't worry about translating to Python.

I would like to have a function callable from a list.

I am tasked with having to create an obtainable item that prints a decoration around a users name. The code for that is in the trophy function. If at all possible i am looking for a way to have a list or tuple that holds callable functions. I feel i have to be able to hold the actual function in the list because i cant think of any other way to be able to select and print(see) the item as is through a list.
Reply
#4
yes example:
def ziggy(name):
    print(f"Hello, I'm {name}")

mylist = ['abc', 'def', ziggy, 'fff']

mylist[2]('Alfie')
Output:
Hello, I'm Alfie
Reply
#5
In Python a variable is a reference to a thing.
x=5     # x is a reference to the integer object 5
y=print # y is a reference to the print function
y(x)    # This is the same as print(5)
Output:
5
Since a collection is just a variable that can reference multiple things, you can do the same kind of things with a list, tuple or dictionary.
alist = [print, 1]
alist[0](alist[1])

atuple = (print, 2)
atuple[0](atuple[1])

adict = {'func':print, 'value':3}
adict['func'](adict['value'])
Output:
1 2 3
There is nothing special about the print function. Any function can be referenced by a variable or a list or a dictionary. You could make a list of functions if you want. One of my favorite examples of a collection of functions is this simple calculator. This time around I defined the operations as lambdas. I could also use the functions defined in the operator library
calc = {
    '+': lambda a, b: float(a)+float(b),
    '-': lambda a, b: float(a)-float(b),
    '*': lambda a, b: float(a)*float(b),
    '/': lambda a, b: float(a)/float(b)
}

while True:
    equation= input('Enter Equation: ')
    if equation:
        a, op, b = equation.split()
        print(f'{a} {op} {b} = {calc[op](a, b)}')
    else:
        break
Output:
Enter Equation: 3 + 4 3 + 4 = 7.0 Enter Equation: 6 / 3 6 / 3 = 2.0 Enter Equation:
Reply
#6
Thank you for that reply.
I can see you are able to index a single value from the examples but what about the entire iteration of the function. I may be missing something but i dont see a way to store a function such as below into a list
def trophy():
  name='KEYS'
  sym='.'
  for i in range(1, len(name)+5, 1):
        print (sym, end="")
  print("\n.."+str(name)+"..")
  for i in range(1, len(name)+5, 1):
        print (sym, end="")
trophy()
and later reference it from the list and get the functions entire output.

also what syntax would be used to add the function to the list. I tried list+=function() but that wasnt right.
Reply
#7
(Nov-09-2020, 02:32 AM)KEYS Wrote: I feel i have to be able to hold the actual function in the list because i cant think of any other way to be able to select and print(see) the item as is through a list.
You can iterate over items in a list and apply a fucntion on each item, no need to have the function in a/the list
e.g.
for item in some_list:
    some_function(item)
or using list comprehension (e.g. if you have a list and want to create new list with elements being the result, i.e. value returned by some function)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#8
I have no idea why or what but I can address this 'adding to list' / 'getting entire function output' part:

>>> def my_func():
...     print('Hello world')
...
>>> list_ = []
>>> list_.append(my_func)
>>> list_[0]()
Hello world
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#9
I still don't see where a list comes into play. What makes you think you need a list of functions? Are you basing this on your trophy function using multiple print()'s? Or is it that you have multiple items in the inventory and will need multiple trophy's? I don't understand what you are asking.

If you can help us understand the problem you are trying to solve I am sure we can provide better answers.
Reply
#10
(Nov-09-2020, 03:49 PM)deanhystad Wrote: I still don't see where a list comes into play. What makes you think you need a list of functions? Are you basing this on your trophy function using multiple print()'s?
yes in a way.
Picture the function as an obtainable object called trophy. I need to be able to have a list of objects like an inventory that can be called on and shown. I will need to have a few other functions that print out a type of art representing an item and have those items stored in a list so they can later be individually selected to view and or view them all.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Programming (identifier, literal and function call) ledangereux 5 4,989 May-05-2020, 12:37 PM
Last Post: gumi543
  Calling function-- how to call simply return value, not whole process juliabrushett 2 3,211 Jul-01-2018, 01:17 AM
Last Post: juliabrushett
  Function call Antonio_Gallardo 3 3,201 Dec-29-2017, 11:13 PM
Last Post: Larz60+
  Error is function call Oracle_Rahul 2 3,149 Sep-21-2017, 06:04 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020