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]
- Python | Ways to sum list of lists and return sum list
- Different ways to clear a list in Python
- Python | Ways to rotate a list
- Python | Ways to Spilt the list by some value
- Python | Ways to flatten a 2D list
- Extending a list in Python (5 different ways)
- Python | Multiply all numbers in the list (3 different ways)
- Python | Ways to find length of list
- Python | Ways to remove particular list element
- Python | Ways to print list without quotes
- Python | Ways to initialize list with alphabets
- Python | Ways to remove duplicates from list
- Python | Ways to merge strings into list
- Python | Ways to format elements of given list
- Python | Ways to create triplets from given list
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.