Shuffling a sequence of numbers have always been an useful utility and the question that has appeared in many company placement interviews as well. Knowing more than one method to achieve this can always be a plus. Let’s discuss certain ways in which this can be achieved.
Method #1 : Fisher–Yates shuffle Algorithm
This is one of the famous algorithms that is mainly employed to shuffle a sequence of numbers in python. This algorithm just takes the higher index value, and swaps it with current value, this process repeats in a loop till end of the list.
The original list is : [1, 4, 5, 6, 3] The shuffled list is : [4, 3, 1, 5, 6]
Method #2 : Using
This is most recommended method to shuffle a list. Python in its random library provides this inbuilt function which in-place shuffles the list. Drawback of this is that list ordering is lost in this process. Useful for developers who choose to save time and hustle.
The original list is : [1, 4, 5, 6, 3] The shuffled list is : [5, 6, 4, 3, 1]
Method #3 : Using
This is quite a useful function, better than the shuffle method used above in aspect that it creates a new shuffled list and returns it rather than disturbing the order of original list. This is useful in cases we require to retain the original list.
The original list is : [1, 4, 5, 6, 3] The shuffled list is : [5, 3, 6, 1, 4]
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.
- Ways to shuffle a Tuple in Python
- Python | Shuffle two lists with same order
- random.shuffle() function in Python
- numpy.random.shuffle() in python
- Shuffle a deck of card with OOPS in Python
- Shuffle an array in Python
- Pandas - How to shuffle a DataFrame rows
- Shuffle a given Pandas DataFrame rows
- Python | Ways to sum list of lists and return sum list
- Python | Ways to Convert a 3D list into a 2D list
- Python | Ways to split a string in different ways
- Python | Convert list of string to list of list
- Python | Convert list of tuples to list of list
- Python | Convert List of String List to String List
- Ways to sort list of dictionaries by values in Python - Using lambda function
- Ways to sort list of dictionaries by values in Python – Using itemgetter
- Extending a list in Python (5 different ways)
- Python | Ways to Spilt the list by some value
- Python | Ways to initialize list with alphabets
- Different ways to clear a list in Python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.