Shuffle List in Python with Examples - Spark By {Examples} (2024)

Spread the love

How to shuffle list elements in Python? A list is an ordered sequence of elements, and the shuffle() function from the built-in random module can be used to shuffle the order of the elements in the Python list. The shuffle() function takes a sequence, such as a list, and modifies it in place by shuffling the order of its elements randomly.

You can shuffle a list in Python using many ways, for example, by using the random.shuffle(), random.sample(), Fisher-Yates shuffle Algorithm, itertools.permutations(), reduce() & numpy, and random.randint() & pop() functions. In this article, I will explain how to shuffle a list by using all these methods with examples.

Sort a List Randomly using Excel Fo...

Sort a List Randomly using Excel Formulas

1. Quick Examples of Shuffle a List

If you are in a hurry, below are some quick examples of how to shuffle a list in Python.

# Quick examples of shuffle a list# Example 1: Shuffle list # Using random.shuffle() functionrandom.shuffle(mylist)# Example 2: Shuffle list # Using random.sample() functionresult = random.sample(mylist, len(mylist))# Example 3: Using Fisher–Yates shuffle algorithm# to shuffle a listfor x in range(len(mylist)-1, 0, -1): y = random.randint(0, x + 1) mylist[x], mylist[y] = mylist[y], mylist[x] # Example 4: Using itertools.permutations() functionpermutations = list(itertools.permutations(mylist))result = random.choice(permutations)# Example 5: Shuffle a list # Using random.randint() and pop() functionn = len(mylist)for i in range(n): j = random.randint(0, n-1) element=mylist.pop(j) mylist.append(element)

2. Python Shuffle List using random.shuffle() Function

The random.shuffle() is a commonly used and recommended method to shuffle a list in Python. This shuffle method actually shuffles the element in place meaning it modifies the original list, hence, the ordering of the original elements in the List is lost. However, this may not be a problem if the original ordering is not important for the specific use case.

2.1 Syntax of random.shuffle()

Following is the syntax of the list random.shuffle().

# Syntax of random.shuffle()random.shuffle(sequence, random)

2.2 Parameters of random.shuffle()

  • sequence – The sequence can be a list, tuple, string, etc.
  • random (optional)- Use function, by default it uses random(). Since version 3.9 it’s been deprecated and removed in version 3.11.

2.3 Shuffle List Example

Following is an example of how to perform a list shuffle. Here, we take a list as input to the shuffle() and it returns shuffle all elements in the input list.

Note that the shuffle method only works with lists, not with other sequence types like tuples or strings as these are immutable.

# Import randomimport random# Initialize listmylist = [5, 10, 20, 30, 40, 50]print("Original list: ", mylist)# Shuffle list # Using random.shuffle() functionrandom.shuffle(mylist)print("Shuffle list: ", mylist)

Yields below output.

Shuffle List in Python with Examples - Spark By {Examples} (1)

3. Using sample() to Shuffle List

Pythonrandom.sample()function is also available in the random module, which will return the random items of a specified length from the iterable objects likelist,string,tuple,set, etc. The random elements from the iterable objects are returned in a list.

3.1 Syntax of random.sample()

Following is the syntax of random.sample() function.

# Syntax of random.sample()random.sample(sequence/iterable, counts, k)

3.2 Parameters of random.sample()

It takes three parameters.

  • sequence:Is the sequence/iterable in which random numbers are generated from this sequence/iterable.
  • counts:It is an optional parameter that will represent the frequency of each element in the specified sequence/iterable. We need to pass the frequencies through a list.
  • k :It is the integer value that will specify the length of the sample. Its length must be less than or equal to the passed iterable object, otherwiseValueErrorwill be raised.

3.3 Return Value

It returns a randomly selected subset of numbers from a given sequence/iterable object.

3.4 Shuffle a List using sample() Example

First import the random module, which provides various functions related to random numbers, and define our original list mylist containing six elements, finally call the random.sample() function and pass in our original list mylist as the first argument and the length of the list as the second argument using the len() function. This returns a new list that contains the elements of the original list in a randomly shuffled order.

# Import randomimport random# Initialize listmylist = [5, 10, 20, 30, 40, 50]print("Original list: ", mylist)# Shuffle list # Using random.sample() functionresult = random.sample(mylist, len(mylist))print("Shuffle list: ", result)

Yields below output.

Shuffle List in Python with Examples - Spark By {Examples} (2)

4. Using Fisher-Yates Shuffle Algorithm

The Fisher-Yates Shuffle Algorithm is also known as the Knuth shuffle algorithm which is widely used to shuffle a sequence of items. This algorithm iterates over the elements of the list in reverse order, starting from the last element and ending at the second element.

At each iteration, it generates a random index within the range of the unshuffled elements and swaps the element at the current index with the element at the randomly generated index. This process is repeated until all the elements in the list have been shuffled.

import random# Initialize listmylist = [5, 10, 20, 30, 40, 50]print("Original list: ", mylist)# Using Fisher–Yates shuffle Algorithm# to shuffle a listfor x in range(len(mylist)-1, 0, -1): y = random.randint(0, x + 1) mylist[x], mylist[y] = mylist[y], mylist[x] print("Shuffle list: ", mylist)

Yields below output.

# Output:Original list: [5, 10, 20, 30, 40, 50]Shuffle list: [40, 20, 10, 30, 50, 5]

The itertools.permutations() function generates all possible permutations of a given sequence, but it does not shuffle the elements of the sequence randomly. If you want to shuffle a list randomly using itertools.permutations(), you can generate all possible permutations and then select one permutation randomly.

For example, define a list [5, 10, 20, 30, 40, 50] that you want to shuffle randomly, then use itertools.permutations() to generate all possible permutations of the list and store them in permutations. You then convert permutations to a list permutations_list so that you can access its elements randomly. Use the random.choice() function to select a random permutation from the result.

# Import modulesimport randomimport itertools# Initialize listmylist = [5, 10, 20, 30, 40, 50]print("Original list: ", mylist)# Using itertools.permutations() functionpermutations = list(itertools.permutations(mylist))result = random.choice(permutations)print("Shuffle list: ", result)# Output: # Original list: [5, 10, 20, 30, 40, 50]# Shuffle list: (30, 40, 10, 20, 5, 50)

6. Using random.randint() and pop() Function

You can also shuffle elements using random.randint() and pop() function. First, you start by getting the length of the list mylist and storing it in the variable n. Then, you loop through the range 0 to n-1 using a for loop. This loop iterates n times.

For each iteration, get the random integer from the list using the randint(), pop that element at the index using pop(), and then append element to the list using append().

# Importimport random# Initialize listmylist = [5, 10, 20, 30, 40, 50]print("Original list: ", mylist) # Shuffle a list # Using random.randint() and pop() functionn = len(mylist)for i in range(n): j = random.randint(0, n-1) element=mylist.pop(j) mylist.append(element)print("Shuffled List: ",mylist)

Yields below output.

# Output:Original list: [5, 10, 20, 30, 40, 50]Shuffled List: [20, 30, 50, 40, 10, 5]

7. Shuffle a List Using reduce() and NumPy

You can also shuffle the elements of a list using the reduce() function from the functools module and the np.random.permutation() function from the NumPy library.

# Importimport numpy as npfrom functools import reduce # Initialize listmylist = [5, 10, 20, 30, 40, 50]print("Original list: " + str(mylist)) # Using reduce() and numpy# To shuffle a listresult = reduce(lambda acc, _: np.random.permutation(acc), range(len(mylist)), np.array(mylist))print("Shuffled list: " + str(result.tolist()))

Yields below output.

# OutputOriginal list: [5, 10, 20, 30, 40, 50]Shuffled list: [20, 5, 30, 50, 40, 10]

Conclusion

In this article, you have learned Python list shuffle can be done by using random.shuffle(), random.sample(), Fisher-Yates shuffle Algorithm, itertools.permutations(), reduce() & numpy, and, random.randint() & pop(). Based on your need, you can use any approach explained in this article.

Happy Learning !!

References

Related Article

  • How to generate random numbers in Python?
  • Random String Generation with Letters and Digits in Python
  • Python random.randint() with Examples
  • Python Random seed() Function
  • Python Random uniform() Function
  • Python Random Module Methods Explained
  • Generate Random Integers Between 0 and 9 in Python
  • Python random.sample() With Examples
  • Python Random randrange() Function
  • Generate Random Float Numbers in Python
  • Python random.choice() function
  • Python random.random() function

You may also like reading:

  1. Python Sort List Alphabetically
  2. How to Sort List of Strings in Python
  3. Python List Methods
  4. Python List Comprehension
  5. Python List index() with Examples
  6. Add String to a List in Python
  7. Check Given Object is a List or not in Python
  8. Python Get the last element of a list
  9. Get Unique Values From a List in Python
  10. Python Replace Values in List With Examples
Shuffle List in Python with Examples - Spark By {Examples} (2024)

FAQs

What is the most efficient way to shuffle a list in Python? ›

shuffle() This method can be one of the most popular ones that are used. All you have to do is import the module random and then call it with a list inside it. It will then change the ordering of the elements in the list and place them randomly there.

How can I shuffle a list in Python? ›

shuffle() function. The shuffle() method in the random module is used to shuffle a list. It takes a sequence, such as a list, and reorganizes the order of the items. This shuffle() method changes the original list, it does not return a new list.

How will you randomizes the items of a list in place? ›

The shuffle() method randomizes the items of a list in place.

How do you shuffle a list in Python without shuffle? ›

03) Sample Method

In this situation, we can use the sample() method that is available in the random library of python. The sampling method does not disturb the original list and returns a shuffled list of all the items in the list.

What is the fastest way to count occurrences in a list in Python? ›

count() is the in-built function by which python count occurrences in list. It is the easiest among all other methods used to count the occurrence.

What is the easiest way to sort a list in Python? ›

The easiest way to sort is with the sorted(list) function, which takes a list and returns a new list with those elements in sorted order. The original list is not changed. It's most common to pass a list into the sorted() function, but in fact it can take as input any sort of iterable collection.

What is the algorithm for random shuffle list? ›

Fisher–Yates shuffle Algorithm works in O(n) time complexity. The assumption here is, we are given a function rand() that generates a random number in O(1) time. The idea is to start from the last element and swap it with a randomly selected element from the whole array (including the last).

How do you randomly shuffle rows in Python? ›

Use pandas. DataFrame. sample(frac=1) method to shuffle the order of rows. The frac keyword argument specifies the fraction of rows to return in the random sample DataFrame.

How do you shuffle a nested list in Python? ›

The 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.

How do you randomize the items of a list in place in Python? ›

The method shuffle() can be used to randomize the items of a list in place. It should be noted that this function is not accessible directly and therefore we need to import or call this function using random static object. Here, 'lst' is passed as a parameter which could be a list or tuple.

Which function is used to shuffle a list? ›

shuffle() function in Python. The shuffle() is an inbuilt method of the random module. It is used to shuffle a sequence (list). Shuffling a list of objects means changing the position of the elements of the sequence using Python.

What is the difference between random sample and random shuffle? ›

shuffle() shuffles the given list in-place. Its length stays the same. random. sample() picks n items out of the given sequence without replacement (which also might be a tuple or whatever, as long as it has a __len__() ) and returns them in randomized order.

What is sample vs shuffle in Python? ›

The shuffle() method takes a sequence of items and rearranges the order of the items. This modifies the original list and does not return anything. The sample() method in Python shuffle list takes a sequence of items and returns a new rearranged list of the desired length. It does not alter the original list.

What is the difference between random choice and shuffle in Python? ›

The choice method only generates one random number, and uses it to index into the sequence it was given. The shuffle method, on the other hand, loops over the length of the sequence and swaps elements around as it goes.

What is the most effective way of starting with 1000 elements in a Python list? ›

The following are some of the ways to initialize lists(we create lists of size 1000 and initialize with zeros) in Python.
  • Using a for loop and append() ...
  • Using a while loop with a counter variable. ...
  • Using list comprehensions. ...
  • Using the * operator.
Oct 29, 2021

What is the complexity of random shuffle in Python? ›

The random. shuffle() function works in O(n) time complexity where n is the number of items in the list. The random. shuffle() function has a space complexity of O(1) as it does not require any extra space.

How do you randomize items of a list in place in Python? ›

The method shuffle() can be used to randomize the items of a list in place. It should be noted that this function is not accessible directly and therefore we need to import or call this function using random static object. Here, 'lst' is passed as a parameter which could be a list or tuple.

References

Top Articles
Latest Posts
Article information

Author: Domingo Moore

Last Updated:

Views: 6025

Rating: 4.2 / 5 (73 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Domingo Moore

Birthday: 1997-05-20

Address: 6485 Kohler Route, Antonioton, VT 77375-0299

Phone: +3213869077934

Job: Sales Analyst

Hobby: Kayaking, Roller skating, Cabaret, Rugby, Homebrewing, Creative writing, amateur radio

Introduction: My name is Domingo Moore, I am a attractive, gorgeous, funny, jolly, spotless, nice, fantastic person who loves writing and wants to share my knowledge and understanding with you.