7

I have a list of strings:

lst = ["orange", "yellow", "green"]    

and I want to randomly repeat the values of strings for a given length.

This is my code:

import itertools
lst = ["orange", "yellow", "green"]
list(itertools.chain.from_iterable(itertools.repeat(x, 2) for x in lst))

This implementation repeats but not randomly and also it repeats equally, whereas it should be random as well with the given length.

3
  • What result do you eexpect ? The length is the global final ? Please clarify with examples in your post Commented Jan 5, 2021 at 10:48
  • Can you be more clear on what you need, Do you want a list that has a random value given in the input list with the same length Commented Jan 5, 2021 at 10:55
  • 1
    i want list of length (1,150) where strings("orange", "yellow" and "green") are repeated randomly i.e, ["orange","yellow","orange","yellow","green",...........,"green"] Commented Jan 5, 2021 at 11:03

2 Answers 2

5

You can use a list comprehension:

import random
lst = ["orange", "yellow", "green"]
[lst[random.randrange(len(lst))] for i in range(100)]

Explanation:

  • random.randrange(n) returns an integer in the range 0 to n-1 included.
  • the list comprehension repeatedly adds a random element from lst 100 times.
  • change 100 to whatever number of elements you wish to obtain.
Sign up to request clarification or add additional context in comments.

Comments

3

One way is to use random.sample():

Return a k length list of unique elements chosen from the population sequence or set.

Simply set k to be 1 each time you call it. This gives you a list of length 1, randomly selected from the source list.

To generate a large random list, repeatedly call random.sample() in a list comprehension, e.g. 150 times. (Of course, you have to also index the resulting list from random.sample() so that you retrieve just the value rather than a list of length 1).

For example:

import random
lst = ["orange", "yellow", "green"]
print([random.sample(lst, k=1)[0] for i in range(150)])
# Output
# ['green', 'orange', 'green', 'yellow', 'green', ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.