Say I have a list x
with unkown length from which I want to randomly pop one element so that the list does not contain the element afterwards. What is the most pythonic way to do this?
I can do it using a rather unhandy combincation of pop
, random.randint
, and len
, and would like to see shorter or nicer solutions:
import random x = [1,2,3,4,5,6] x.pop(random.randint(0,len(x)-1))
What I am trying to achieve is consecutively pop random elements from a list. (i.e., randomly pop one element and move it to a dictionary, randomly pop another element and move it to another dictionary, ...)
Note that I am using Python 2.6 and did not find any solutions via the search function.
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.
The set pop() is a built-in Python method that removes the random element from the set and returns the removed element. The pop() method does not pop from the back or front; it can pop any element from anywhere present in the set. Unlike the stack, a random element is popped off the set.
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.
To select a random element from a list in python, we can use the choice() function defined in the random module. The choice() function takes a list as input and returns a random element from the list every time it is executed.
What you seem to be up to doesn't look very Pythonic in the first place. You shouldn't remove stuff from the middle of a list, because lists are implemented as arrays in all Python implementations I know of, so this is an O(n)
operation.
If you really need this functionality as part of an algorithm, you should check out a data structure like the blist
that supports efficient deletion from the middle.
In pure Python, what you can do if you don't need access to the remaining elements is just shuffle the list first and then iterate over it:
lst = [1,2,3] random.shuffle(lst) for x in lst: # ...
If you really need the remainder (which is a bit of a code smell, IMHO), at least you can pop()
from the end of the list now (which is fast!):
while lst: x = lst.pop() # do something with the element
In general, you can often express your programs more elegantly if you use a more functional style, instead of mutating state (like you do with the list).
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