Hi I have a List say 100 items, now i want a slice of say 6 items which should be randomly selected. Any way to do it in very simple simple concise statement???
This is what i came up with (but it will fetch in sequence)
mylist #100 items
N=100
L=6
start=random.randint(0,N-L);
mylist[start:start+L]
Use the random.sample() function when you want to choose multiple random items from a list without repetition or duplicates. There is a difference between choice() and choices() . The choices() was added in Python 3.6 to choose n elements from the list randomly, but this function can repeat items.
Select randomly n elements from a list using choice() The choice() method is used to return a random number from given sequence. The sequence can be a list or a tuple. This returns a single value from available data that considers duplicate values in the sequence(list).
We can initialize a list of size n using a range() statement. The difference between using a range() statement and the None method is that a range() statement will create a list of values between two numbers. By default, range() creates a list from 0 to a particular value.
You can use this: [None] * 10 . But this won't be "fixed size" you can still append, remove ... This is how lists are made. You could make it a tuple ( tuple([None] * 10) ) to fix its width, but again, you won't be able to change it (not in all cases, only if the items stored are mutable).
You could use the shuffle()
method on the list before you slice.
If the order of the list matters, just make a copy of it first and slice out of the copy.
mylist #100 items
shuffleList = mylist
L=6
shuffle(shuffleList)
start=random.randint(0,len(shuffleList)-L);
shuffleList[start:start+L]
As above, you could also use len() instead of defining the length of the list.
As THC4K suggested below, you could use the random.sample() method like below IF you want a set of random numbers from the list (which is how I read your question).
mylist #100 items
L=6
random.sample(mylist, L)
That's a lot tidier than my first try at it!
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