w3resource

Python: Select a random element from a list, set, dictionary and a file from a directory

Python module: Exercise-2 with Solution

Write a Python program to select a random element from a list, set, dictionary-value, and file from a directory.

Use random.choice

Sample Solution:

Python Code:

import random
import os
print("Select a random element from a list:")
elements = [1, 2, 3, 4, 5]
print(random.choice(elements))
print(random.choice(elements))
print(random.choice(elements))
print("\nSelect a random element from a set:")
elements = set([1, 2, 3, 4, 5])
# convert to tuple because sets are invalid inputs
print(random.choice(tuple(elements)))
print(random.choice(tuple(elements)))
print(random.choice(tuple(elements)))
print("\nSelect a random value from a dictionary:")
d = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}
key = random.choice(list(d))
print(d[key])
key = random.choice(list(d))
print(d[key])
key = random.choice(list(d))
print(d[key]) 
print("\nSelect a random file from a directory.:")
print(random.choice(os.listdir("/")))

Sample Output:

Select a random element from a list:
3
4
5

Select a random element from a set:
1
3
5

Select a random value from a dictionary:
5
4
4

Select a random file from a directory.:
proc

Flowchart:

Flowchart: Select a random element from a list, set, dictionary and a file from a directory.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to generate a random color hex, a random alphabetical string, random value between two integers (inclusive) and a random multiple of 7 between 0 and 70.
Next: Write a Python program to generate a random alphabetical character, alphabetical string and alphabetical string of a fixed length.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/modules/python-module-random-exercise-2.php