Home > Back-end >  Is there a better way to write this random list function?
Is there a better way to write this random list function?

Time:12-23

Traceback (most recent call last):
  File "main.py", line 9, in <module>
    rand = random.randint(0,place)
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/random.py", line 248, in randint
    return self.randrange(a, b 1)
TypeError: can only concatenate str (not "int") to str

^This is my error. I'm not sure why this code isn't working as I'm new to Python. I'm trying to write a code that detects how big a list is, then selects a random item from the list.

import random

greetings = ["hello","hola","bonjour","privet","ciao","guten tag","shalom"]

place = 0
for i in greetings:
  place = i

rand = random.randint(0,place)
print(greetings[rand])

^This is what I have so far. Any help would be appreciated

CodePudding user response:

Don't reinvent the wheel. The random module has choice() function exactly for this purpose:

print(random.choice(greetings))

CodePudding user response:

This snippet:

place = 0
for i in greetings:
  place = i

Boils down to just being a really complicated way of getting the last list element of grettings, which probably isn't what you expected nor wanted. The name i might suggest that you thought these were index integers, but in fact, the value of i is just each greeting in the list. Each one is written to place in order, and only the last value sticks. I.e. for your particular greetings array, the value of place will always end up as "shalom".

This returns the following line into rand = random.randint(0, "shalom"), which clearly makes no sense.

A correct (but bad) example might actually iterate over the indices:

last_list_index = 0 # Renamed from "place" for clarity 
for i in range(greetings):
  last_list_index = i

list_length = last_list_index   1
random_index = random.randint(0, list_length)
print(greetings[random_index])

But of course, that's convoluted too. Why waste time iterating over all the indices to just get the last one? You can just call len(greetings) to get the list length directly:

random_index = random.randint(0, len(greetings))
print(greetings[random_index])

But wait, there's more! There's a more specific tool for the job that is made for exactly this:

import random

greetings = ["hello","hola","bonjour","privet","ciao","guten tag","shalom"]

random_greeting = random.choice(greetings)
print(random_greeting)
  • Related