Randomizing a list of tuples without random.shuffle() python

I have a list of tuples looking like... deck=[(1,'clubs'),(1,'hearts')...and so on to (13,'diamonds').

How do I randomize this list into something like...

[(5,'spades'),(12,'clubs'),(3,'clubs'),... and so on?

I have tried using random.randint() and nothing seems to work. And I can not use random.shuffle()

You want random.shuffle():

>>> import random
>>> l = [1, 2, 3, 4, 5]
>>> random.shuffle(l)
>>> l
[2, 1, 5, 3, 4]

Since it seems you can't use random.shuffle, perhaps your teacher wanted you to use random.randint() to get a random number between 1-13, then a random suit (hearts, clubs, diamonds, spades), and form a list like that. Keep in mind you'll need to check if the card already exists in the list.

Try have an attempt first, but if you can't do it, then here's the solution. I strongly recommend you have a go first using the approach I just mentioned above.

l = []
while len(l) < 52:
    number = random.randint(1, 13)
    suit = random.choice(['hearts', 'clubs', 'diamonds', 'spades'])
    card = (number, suit)
    if card not in l:
        l.append(card)

Shuffle a list, string, tuple in Python (random.shuffle, sample), To randomly shuffle elements of lists (list), strings (str) and tuples (tuple) in random provides shuffle() that shuffles the original list in place, and If you want to sort in ascending or descending order or reverse instead of shuffling, see the s = 'abcde' # random.shuffle(s) # TypeError: 'str' object does not� Read More: random.sample() Warning:. If we use to shuffle not in place to get the shuffled list back i.e., random.sample(x, len(x)) instead of random.shuffle(x) As per the official Python documentation, for small len(x), the total number of permutations of x can quickly grow larger than the period of most random number generators.

If you want to shuffle a pre-existing list, rather than creating it already shuffled, it's not hard to do work fairly similar to what random.shuffle likely does (I'm intentionally avoiding checking the source code to avoid guilty knowledge here):

deck = [(1,'clubs'),(1,'hearts')...]
for i, card in enumerate(deck):
    swapi = random.randrange(i, len(deck))
    deck[i], deck[swapi] = deck[swapi], card

All that does is swap each card in the deck with a card at or after it, and by doing so for every card, the end result maintains none of the order of the original deck.

Python random.shuffle() to Shuffle List, Python random.shuffle() function to shuffle list x is any sequence you want to shuffle. x can be the list, string or tuple. If not specified by default, Python uses random.random() function. i.e., it randomizes the order of items in a list, we call it a randomizes the elements of a list in place. for example,� Python | Select a random item from a list in Python; How to pick a random card in Python; Shuffle the elements in a list in Python using random module. In the random module, we got method random.shuffle() random.shuffle() can be used to shuffle object. Pass the object whose elements you want to shuffle in the method. import random a_list =['545

   import time
   test_list = [r for r in range(20)]
   print("The original list is : " + str(test_list))
   for i in range(len(test_list)):
    n=str(time.time())[-1]
    j=int(n)

    # Swap arr[i] with the element at random index
    if j < len(test_list):
     test_list[i], test_list[j] = test_list[j], test_list[i]

   print("The shuffled list is : " + str(test_list))

Python, Shuffling a sequence of numbers have always been an useful utility and the Method #2 : Using random.shuffle() This is most recommended method to shuffle a list. Python in its random library provides this inbuilt function which to remove duplicates from list � Python | Ways to print list without quotes� Method #2 : Using random.shuffle() This is most recommended method to shuffle a list. Python in its random library provides this inbuilt function which in-place shuffles the list.

Python Random shuffle() Method, Can be a list, a tuple, or a string. function, Optional. The name of a function that returns a number between 0.0 and 1.0. If not specified, the function random() will � random.shuffle (x [, random]) ¶ Shuffle the sequence x in place. The optional argument random is a 0-argument function returning a random float in [0.0, 1.0); by default, this is the function random(). To shuffle an immutable sequence and return a new shuffled list, use sample(x, k=len(x)) instead.

Shuffling sections of an ordered list based on tuple values, python algorithm shuffle random.shuffle(temp) new_pieces_needed += temp current_freq = object() for piece in pieces_needed: freq = piece[1] if freq The same general algorithm would work for any kind of data, not just� The pythonic way to select a single item from a Python sequence type — that's any of str, unicode, list, tuple, bytearray, buffer, xrange — is to use random.choice. For example, the last line of our single-item selection would be:

Python 3 - Number shuffle() Method, The shuffle() method randomizes the items of a list in place. Syntax. Following is the syntax for shuffle() method − shuffle (lst,[random]). Note − This function is not accessible directly, so we need to import shuffle module and then we need to call this function using random static object. lst − This could be a list or tuple. The choice function can often be used for choosing a random element from a list. import random myList = [2, 109, False, 10, "Lorem", 482, "Ipsum"] random.choice(myList) Shuffle. The shuffle function, shuffles the elements in list in place, so they are in a random order. random.shuffle(list) Example taken from this post on Stackoverflow

Comments
  • Are you allowed to use anything from the random module?
  • I am not allowed to use random.shuffle() is there another way?
  • @DrakeRobison Why aren't you allowed to use random.shuffle?
  • Oh, I think I know what approach your teacher wants. Let me work something out
  • @DrakeRobison Sorry it took so long. I was trying to format my answer so that there would be a spoiler tag so you would have a go. I strongly recommend you have a go first with the explanation I included in my answer
  • @TerryA: I had downvoted this answer because it did not answer the actual question that the OP asked, i.e. how to shuffle a pre-existing list without using random.shuffle(). However, because the OP now says it's what was wanted, I have retracted the down vote.
  • I've been told by a more experienced colleague to avoid this kind of method. Apparently its much better to use Numpy to achieve this instead. See: blog.codinghorror.com/the-danger-of-naivete
  • @LaurieBamber: This is not the naive solution mentioned in your link. That solution swaps each location once with every other possible location (that is, it swaps index 0 with a random index from 0 to n, then index 1 with a random index from 0 to n, etc.). My solution, by using random.randrange(i, len(deck)) (not randrange(len(deck))), ends up with the same combinatoric properties as the Knuth-Fisher-Yates shuffle in your link, swapping 0 with 0-n, then 1 with 1-n, etc., essentially selecting a single value to occupy each slot from the set of unselected values remaining as it goes.
  • As for using numpy, the OP was explicitly forbidden to use random.shuffle; I doubt using numpy equivalents would be acceptable.
  • Fair enough, I don't know enough to comment about this, my colleague just said he thought this method might produce the same problems as listed in the provided article. Is random part of the numpy library? I though random was seperate.
  • @LaurieBamber: You brought up numpy as a better way to achieve this, which is the only reason I mentioned it; no, random and numpy.random aren't the same, but they're both predefined APIs that do the work for you, and the OP was trying to implement without using a predefined API (as the teacher forbade it). If they're that early in their Python class, jumping to numpy (third party, more magical than the Python builtins) isn't going to teach them the right approach.