Home » Python

Print random elements using random.choice() function in Python

Python - random.choice() function with Example: In this article, we are going to learn about choice() function which is an in-built function of random module in Python with example.
Submitted by IncludeHelp, on January 21, 2018

Python - random.choice() function

random() is an in-built function of 'random' module in Python, it is used to return a random element from a container like object like lists, string, tuple etc.

In the given program, we are using string and list and generating random number from the list, random string from the list of strings and random character from the string. To use 'random' module we need to import 'random'.

Import statement: import random

Syntax: random.choice(container_type_object)

Here, container_type_object may a string, list of numbers, list of strings, tuple etc.

Example:

    Input string: "Hello"
    
    Output (May different)
    e - first time
    H - second time

# Python code to generate random element (an example of random.choice() function)

# Python code to generate random element
# an example of random.choice() function
    
# import statement
import random

# defining string
str_var = "Hello!"
# defining list of numbers
num_list = [10, 20, 30, 40, 50]
# defining list of strings
str_list = ["Hello", "Hi", "Bye"]

# Generating & pritning 3 random
# characters from string 'str_var'
print "Random chars from string: ", str_var
print random.choice(str_var)
print random.choice(str_var)
print random.choice(str_var)

# Generating & pritning 3 random
# numbers from number list 'num_list'
print "Random numbers from num list: ", num_list
print random.choice(num_list)
print random.choice(num_list)
print random.choice(num_list)

# Generating & pritning 3 random
# strings from strings list 'str_list'
print "Random strings from strings list: ", str_list
print random.choice(str_list)
print random.choice(str_list)
print random.choice(str_list)

Output

Random chars from string:  Hello!
o
l
e
Random numbers from num list:  [10, 20, 30, 40, 50]
40
20
40
Random strings from strings list:  ['Hello', 'Hi', 'Bye']
Hi
Hi
Bye




Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.