Welcome to the Treehouse Community
Looking to learn something new?
Pick a number challenge
Stuck here. Here is my code thus far:
import random minus_one =  def random_member(): x = len(minus_one) num = random.randint(0,x) return
Stone Preston42,016 Points
it looks like you misunderstood the instructions a bit.
it says Now, make a function named random_member that takes a list. It should generate a random number between zero and the length of the list (minus one), and return the list item at that index..
So your function needs to take a list argument (currently yours takes no arguments). it needs to generate a random number between zero and the length of the list passed in minus one, (the list isnt called minus one though, this is where you misunderstood). then return the item in the list at the index of the random number
import random def random_member(some_list): # x is the upper bound of the random function. it needs to equal the length of the list - 1 so we dont go out of index in the list x = len(some_list) - 1 #num is the random number generated by the random function. it will be between 0 and the length of the list argument passed in - 1 num = random.randint(0,x) # returns the list item at the random index return some_list[num]
after a while of trial and error i finally cracked it...
def random_num(num): return random.randint(1, num)
remember we already have 1, so I used (num) as my argument. then 'return'
Ann Cascarano17,191 Points
The random number that you are going to generate using the randint method will be used as an index to extract a given number from your list. You never know what index you are going to get - and thus - you don't know which number from the list it will pull out.
Now - because we know that indexes are 0-based - you need your pool of numbers from which your random generator will draw from to include 0, 1, 2, 3 and so on until all the elements in the list have been accounted for. When you are using the len method on a list, for example, you are counting the number of elements in the list - and here is the tricky part: A list of 4 items will have the indexes 0, 1, 2, 3. Therefore - in order to use your randint method to produce a valid random index for your list, you have to remove 1 from the length of the list.
your_list = [1, 2, 3, 4, 5]
random_num = randint (0, (len (your_list) - 1))
If you omit the '-1', your random_num will eventually give you a '5' - and since there is no 5th index in the list, the program will crash.
Hope this helps!
Hi there, quick question regarding this challenge.
Why do we use:
rather than just: return some_list