Python: Shuffle the elements of a given listLast update on May 18 2021 06:46:43 (UTC/GMT +8 hours)Python | Ways to shuffle a listShuffling 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. Show
Table of Contents
Table of Contents
Python3 # Python3 code to demonstrate # shuffle a list # using Fisher–Yates shuffle Algorithm import random # initializing list test_list = [1, 4, 5, 6, 3] # Printing original list print ("The original list is : " + str(test_list)) # using Fisher–Yates shuffle Algorithm # to shuffle a list for i in range(len(test_list)-1, 0, -1): # Pick a random index from 0 to i j = random.randint(0, i + 1) # Swap arr[i] with the element at random index test_list[i], test_list[j] = test_list[j], test_list[i] # Printing shuffled list print ("The shuffled list is : " + str(test_list)) Output: The original list is : [1, 4, 5, 6, 3] The shuffled list is : [4, 3, 1, 5, 6]
Python3 # Python3 code to demonstrate # shuffle a list # using random.shuffle() import random # initializing list test_list = [1, 4, 5, 6, 3] # Printing original list print ("The original list is : " + str(test_list)) # using random.shuffle() # to shuffle a list random.shuffle(test_list) # Printing shuffled list print ("The shuffled list is : " + str(test_list)) Output: The original list is : [1, 4, 5, 6, 3] The shuffled list is : [5, 6, 4, 3, 1]
Python3 # Python3 code to demonstrate # shuffle a list # using random.sample() import random # initializing list test_list = [1, 4, 5, 6, 3] # Printing original list print ("The original list is : " + str(test_list)) # using random.sample() # to shuffle a list res = random.sample(test_list, len(test_list)) # Printing shuffled list print ("The shuffled list is : " + str(res)) Output: The original list is : [1, 4, 5, 6, 3] The shuffled list is : [5, 3, 6, 1, 4] Method 4: In this method we select a index randomly and append that element at that index to the list. Python3 import random # Assign array arr = [1, 2, 3, 4, 5, 6] # Display original array print("Original List: ", arr) # Get length of List n = len(arr) #repeat the following for n number of times for i in range(n): #select an index randomly j = random.randint(0, n-1) #delete the element at that index. element=arr.pop(j) #now append that deleted element to the list arr.append(element) print("Shuffled List: ",arr) Output Original List: [1, 2, 3, 4, 5, 6] Shuffled List: [4, 5, 3, 2, 6, 1] 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. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course Article Tags : Python Python list-programs python-list Practice Tags : python-list Read Full Article Python Random shuffle() Method❮ Random Methods ExampleShuffle a list (reorganize the order of the list items): import random mylist = ["apple", "banana", "cherry"] print(mylist) Try it Yourself » How to Shuffle and Return a New List?The default random.shuffle(a) method modifies an existing list a. It works in-place. So, what if you want to shuffle the original list but return a new list while leaving the original list elements unchanged? No problem—use slicing to copy the list. import random a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] b = a[:] random.shuffle(b) print(b)Exercise: Take a guess—what’s the output of this code snippet? You can check your guess in our interactive code shell: Related articles:
Where to Go From Here?Enough theory. Let’s get some practice! Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation. To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs? You build high-value coding skills by working on practical coding projects! Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people? If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner. Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home. Join the free webinar now! While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students. To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide. His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here. Shuffle a list, string, tuple in Python (random.shuffle, sample)Posted: 2020-02-05 / Tags: Python, List Tweet To randomly shuffle elements of lists (list), strings (str), and tuples (tuple) in Python, use the random module.
random provides shuffle() that shuffles the original list in place, and sample() that returns a new list that is randomly shuffled. sample() can also be used for strings and tuples.
If you want to sort in ascending or descending order or reverse instead of shuffling, see the following articles.
What is the Difference Between .shuffle and .sample?Python comes built-in with an incredibly helpful library to generate randomness, called random. Throughout this tutorial, you’ll learn how to use the random.shuffle() and random.sample() functions. Before we dive into how to use them, however, let’s quickly explore what the differences are. Both functions return a list that is randomly sorted, but how they return them is different:
random.sample() can also be used to shuffle strings and tuples, as it creates a new list, thereby allowing you to work on immutable data types. Now, let’s dive into how to shuffle a list in Python! Check out some other Python tutorials on datagy, including our complete guide to styling Pandas and our comprehensive overview of Pivot Tables in Pandas! Shuffle a Python List and Re-assign It to ItselfThe random.shuffle() function makes it easy to shuffle a list’s items in Python. Because the function works in-place, we do not need to reassign the list to itself, but it allows us to easily randomize list elements. Let’s take a look at what this looks like: # Shuffle a list using random.shuffle() import random a_list = ['welcome', 'to', 'datagy', 'where', 'you', 'will', 'learn', 'Python', 'and', 'more'] random.shuffle(a_list) print(a_list) # Returns: ['more', 'will', 'Python', 'welcome', 'learn', 'you', 'where', 'to', 'datagy', 'and'] What we’ve done here is:
Keep in mind, if you’re following along with the example above, your randomly sorted list will probably look different! In the next section, you’ll learn how to use the random.sample() function to randomize a list in Python. Want to learn more about Python list comprehensions? Check out this in-depth tutorial that covers off everything you need to know, with hands-on examples. More of a visual learner, check out my YouTube tutorial here. Write a Python program to shuffle all the elements in a given seriesPythonPandasServer Side ProgrammingProgramming Assume, you have a dataframe and the result for shuffling all the data in a series, The original series is 0 1 1 2 2 3 3 4 4 5 dtype: int64 The shuffled series is : 0 2 1 1 2 3 3 5 4 4 dtype: int64 |