Random and sequences shuffle choice and sample

suggest change
import random

shuffle()

You can use random.shuffle() to mix up/randomize the items in a mutable and indexable sequence. For example a list:

laughs = ["Hi", "Ho", "He"]

random.shuffle(laughs)     # Shuffles in-place! Don't do: laughs = random.shuffle(laughs)

print(laughs)
# Out: ["He", "Hi", "Ho"]  # Output may vary!

choice()

Takes a random element from an arbitary sequence:

print(random.choice(laughs))
# Out: He                  # Output may vary!

sample()

Like choice it takes random elements from an arbitary sequence but you can specify how many:

#                   |--sequence--|--number--|
print(random.sample(    laughs   ,     1    ))  # Take one element
# Out: ['Ho']                    # Output may vary!

it will not take the same element twice:

print(random.sample(laughs, 3))  # Take 3 random element from the sequence.
# Out: ['Ho', 'He', 'Hi']        # Output may vary!

print(random.sample(laughs, 4))  # Take 4 random element from the 3-item sequence.
ValueError: Sample larger than population

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Random module:
* Random and sequences shuffle choice and sample

Table Of Contents
2 Filter
3 List
7 Loops
8 Random module
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve