Python Forum
Question about the Random Module
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Question about the Random Module
#1
random.choice() returns an element, while random.choices() (with an s) returns a list. I need to use choices, because that allows me to use weights, but I want to return an element rather than a list. Is there a simple way to get an element instead of a list? I've been using a for loop or index positions (see below), but there has to be something easier, right?

I'm really, really new at Python, so please be as simple and non-technical as you can in your replies. Thanks in advance!

Example code:
import random
list1 = ["this", "that", "the other"]

choice1 = random.choice(list1)
choice2 = random.choices(list1)
choice2 = choice2[0]

print(choice1)
print(choice2)
Reply
#2
Line 6 of your code really is the simple way. You can combine it with the call to choices to make a one-liner:

choice2 = random.choices(list1)[0]
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  datetime module question jacksfrustration 10 1,608 Jan-12-2024, 04:54 AM
Last Post: deanhystad
  Module not found question sighhhh12 0 1,448 Sep-09-2022, 05:43 AM
Last Post: sighhhh12
  Question on subprocess module. knoxvilles_joker 3 2,622 Apr-11-2021, 12:51 AM
Last Post: knoxvilles_joker
  keyboard module question DPaul 0 2,110 Mar-23-2021, 04:22 PM
Last Post: DPaul
  <while> cycle is not interrupted when using the <random>module ShityCoder 3 2,106 Sep-04-2020, 04:05 PM
Last Post: ShityCoder
  random question DPaul 2 1,938 Jul-22-2020, 07:40 AM
Last Post: DPaul
  Some help with Classes and the random module please? :) AlluminumFoil 2 2,136 Jan-08-2020, 11:03 PM
Last Post: AlluminumFoil
  Can't Get Random Module! Pls Help! VictorVictus 1 7,058 Aug-24-2019, 10:20 AM
Last Post: snippsat
  Module googletrans 2.4.0 Question hlhp 0 2,552 Jun-17-2019, 03:50 PM
Last Post: hlhp
  Random module Python 3.6 daryl_uk 1 2,210 Oct-25-2018, 12:09 AM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020