Friday, April 6, 2012

Python: How to remove, or pop an element randomly from a list

Reference: http://stackoverflow.com/q/10048069/1276534
Credit: Henrik, F.J, Óscar López, Niklas B.

Assuming you want to randomly remove an element from your list, you can use the random module, to generate a random number, between the valid index in your list. Take a look at the code below.
# Import the random module
import random

# This is your list with some number
# But you can of course have anything you in your list
myList = [1, 3, 5, 7, 9, 11]

# Method #1
myList.pop(random.randrange(len(myList)))

# Method #2 (This one will change your list)
random.shuffle(myList)
# While my list is not empty
while myList:
    myList.pop

(Method 1) Let's studying this code from the inner to the outer layer.
  1. We get the length of the list, with my len(myList)
  2. Then we call randrange(), what randrange does it return a number that is pick randomly between the range we provide it. But except we do not actually create this list. Like range() would.
  3. Then finally we pop it from our list.
(Method 2) This will be good, if you want to use your list all together, instead of just popping one element. This is used in the csci133 example in the playing deck, since you have to shuffle your whole deck and then pick 1 card at a time. It make sense to have it shuffled.

    1 comment:

    1. Wynn Hotel and Casino | Joliet, Illinois - JTA Hub
      View 경상북도 출장안마 deals 안산 출장안마 for Wynn Hotel and Casino, including fully 서울특별 출장샵 refundable rates 보령 출장안마 with free cancellation. 구미 출장마사지 Guests enjoy the locale.

      ReplyDelete