()
Yes Python standard libraryrandom
A function in the module to randomly select an element from a non-empty sequence.
1. Basic syntax
import random (sequence)
Parameter description
-
sequence
: A non-empty iterable sequence, such as:list
、tuple
、string
。 - Return value: Returns a random element from the sequence.
2. Example usage
2.1 Randomly select from the list
import random colors = ["red", "green", "blue", "yellow"] print((colors))
Possible output:
green
2.2 Randomly select a character from a string
import random s = "abcdefg" print((s))
Possible output:
e
2.3 Randomly select from tuples
import random options = (10, 20, 30, 40) print((options))
Possible output:
30
3. Things to note
-
()
Only used for non-empty sequences, otherwise it will be thrownIndexError
:
([]) # IndexError: Cannot choose from an empty sequence
- If you want to get from the collection (
set
) or dictionary (dict
) randomly select elements in ) and can be converted tolist
:
(list(my_set)) (list(my_dict.keys()))
4. Compare with other functions
function | Function |
---|---|
(seq) | Select a random element from the sequence |
(seq, k=3) | Randomly select multiple elements from the sequence (repeatable) |
(seq, k=3) | Randomly select multiple elements from the sequence (no duplicate) |
(a, b) | Returns a random integer in the range [a, b] |
() | Returns a random floating point number in the range [0.0, 1.0) |
5. Summary
-
()
It is a simple way to randomly select an element from a non-empty sequence. - It is often used in simulation lottery, random test data, game development and other scenarios.
- When using it, make sure that the sequence is not empty and the type is
list
、tuple
、str
wait.
This function is a "drawing lottery tool" in Python's random functions, which is simple and efficient.
This is the end of this article about the use of() functions in Python. For more related Python () content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!