Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Variable with x number of strings from list in Python

Say that I had a list containing 5 strings, and I wanted to print a random number of randomly generated strings from this list. Is there a simple way to do this?

I know multiple ways to print a single random string from this list, and multiple ways to print a set number of random strings from this set. The problem comes from wanting to print a random number of random strings from the list.

To get a set number of random strings (let’s say 2) I would do the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 import random
 my_list = ['a','b','c','d','e']
 two_rand_strings = str(my_list[random.randint(0,4)]) + " " + str(my_list[random.randint(0,4)])
 print(two_rand_strings)

I assume I need to create some sort of function to generate a random number of strings but I am new to python and scratching my head.

>Solution :

There is an API for that.

The random module has several options to select from a population such as a list. And if you want use use the same separator for each item in the string result, you can str.join them.

import random
my_list = ['a','b','c','d','e']
unique = " ".join(random.sample(my_list, k=2))
nonunique = " ".join(random.choices(my_list, k=2))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading