Python Forum
list - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: list (/thread-15533.html)



list - josesalazmit - Jan-20-2019

Hello (Please, follow my code below)
This is a portion of a code which use list and function and I took part of the code to best understand the concept
I created a list "palabras" and I assigned there several words

then, I created a function which receive the argument "listaDePalabras"
that argument takes the value when I call the function with:
zona = obtenerPalabraAlAzar(palabras)

inside the function I use the function random to take randomly a word from the list "palabras"
then , I assigned the value in the variable "indiceDePalabras" which return and assign to variable zone to allow print it
But it doesn't work
the error shows:
"list" object is not callable

In short, I want to print a random word from the list using a call from the function

What do I missing here?

I will appreciate any help

Regards,

Jose

Please, follow my code below

import random


palabras = 'hormiga babuino tejon murcielago oso castor camello gato almeja cobra pantera coyote cuervo ciervo perro burro pato aguila huron zorro rana cabra ganso halcon leon lagarto llama topo mono alce raton mula salamandra nutria buho panda loro paloma piton conejo carnero rata cuervo rinoceronte salmon foca tiburon oveja mofeta perezoso serpiente araña cigüeña cisne tigre sapo trucha pavo tortuga comadreja ballena lobo wombat cebra'.split()


def obtenerPalabraAlAzar(listaDePalabras):
    indiceDePalabras = random.randint(0,len(listaDePalabras)-1)
    return listaDePalabras(indiceDePalabras)


zona = obtenerPalabraAlAzar(palabras)

print(zona)



RE: list - Larz60+ - Jan-20-2019

actual with code numbers would be more helpful
somewhere you are trying to access the list with listname()
where it should be listname
to get an item from within the list, it's listname[index]


RE: list - ichabod801 - Jan-20-2019

Please use python and output tags when posting code and results. I put them in for you this time. Here are instructions for doing it yourself next time.


RE: list - stullis - Jan-20-2019

With your existing code, you just need to change the parentheses to square brackets in the return. However, it would be more straightforward to use random.choice() instead:

def obtenerPalabraAlAzar(listaDePalabras):
    indiceDePalabras = random.randint(0,len(listaDePalabras)-1)
    return listaDePalabras[indiceDePalabras]

# or

def obtenerPalabraAlAzar(listaDePalabras):
    return random.choice(indiceDePalabras)