Is there a pythonic way to slice a sequence type such that the returned slice is of random length and in random order? For example, something like:
>>> l=["a","b","c","d","e"]
>>> rs=l[*:*]
>>> rs
['e','c']
Slicing in Python is a feature that enables accessing parts of sequences like strings, tuples, and lists. You can also use them to modify or delete the items of mutable sequences such as lists. Slices can also be applied on third-party objects like NumPy arrays, as well as Pandas series and data frames.
You can use random. randint() and random. randrange() to generate the random numbers, but it can repeat the numbers. To create a list of unique random numbers, we need to use the sample() method.
In Python, you can randomly sample elements from a list with choice() , sample() , and choices() of the random module. These functions can also be applied to a string and tuple. choice() returns one random element, and sample() and choices() return a list of multiple random elements.
You can slice sequences to create new sequences of the same type containing subsets of the original elements. Slice operations can modify mutable sequences—those that do not modify a sequence work identically for lists, tuples and strings.
How about...
random.sample(l, random.randint(1, len(l)))
Quick link to docs for the random module can be found here.
No idiom that I'm aware of, but random.sample
does what you need.
>>> from random import sample, randint
>>>
>>> def random_sample(seq):
... return sample(seq, randint(0, len(seq)))
...
>>> a = range(0,10)
>>> random_sample(a)
[]
>>> random_sample(a)
[4, 3, 9, 6, 7, 1, 0]
>>> random_sample(a)
[2, 8, 0, 4, 3, 6, 9, 1, 5, 7]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With