What is the most pythonic way to pop a random element from a list?
list, python, random
Solution
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).
Problem
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.