Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Creating random.choice()

I wrote random.choice() from scratch and it doesn't seem to be working. However it does work perfectly in the shell.

import random
num_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def random_item(num_list)
   return random.randint(0, len(num_list) -1 )
random_item(num_list)

Where is it not working?

2 Answers

After posting I realized that you're only returning a random index into the list but not the actual value at that index.

Something like this might be what you're after:

import random
num_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def random_item(num_list)
  idx = random.randint(0, len(num_list) -1 )
  return num_list[idx]
random_item(num_list)

I think a better return value would be:

return num_list[random.randint(0, len(num_list) -1 )]