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 Python Collections (Retired) Dungeon Game Random Choices

Alex Rodriguez
seal-mask
.a{fill-rule:evenodd;}techdegree
Alex Rodriguez
Front End Web Development Techdegree Student 20,810 Points

I got the code challenge right but there must be a better way.

Here is the challenge: Create a function named nchoices() that takes an iterable and an integer. The function should return a list of n random items from the iterable where n is the integer. Duplicates are allowed.

Here is my code:

import random

def nchoices(some, thing): rand_list = [] for item in some: rand_list.append(random.choice(some)) rand_list.append(random.choice(some)) rand_list.append(random.choice(some)) rand_list.append(random.choice(some)) rand_list.append(random.choice(some)) return rand_list

This code surprisingly worked, but I am repeating my self way too much and didn't even use the integer.

Could someone please show me how I can accomplish the same task but more efficiently.

Thank you

2 Answers

Hi Alex,

We begin by importing the random library and defining the function with two arguments: an iterable and an integer. Then we create an empty list to store the random items in. In order to pull out random items from the iterable, we use a for loop. Since we only want a limited amount of items in our list -- defined by the integer argument --, we check to see if the length of our list is less than the integer argument. If it is, we append the item to our list -- a random choice from the iterable. Otherwise we simply return the list. It's important to give your arguments helpful names, so keep that in mind. Happy coding!

import random


def nchoices(iterable, integer):  # define function
  list1 = []  # create empty list
  for item in iterable:  # for loop
      if len(list1) < integer:  # is the length of the list less than the value of the integer?
          list1.append(random.choice(iterable))  # append the random choice to our list
      else:  # if the length of our list is not less than the integer argument,
          return list1  # return the list