How to shuffle list python

How to shuffle a list of objects in Python?

In this article, we will show you how to shuffle a list of objects in python. Below are the various methods to accomplish this task:

  • Using random.shuffle() function
  • Using random.sample() function
  • Using Fisher–Yates shuffle Algorithm
  • Using random.randint() and pop() function

Assume we have taken a list containing some elements. We will shuffle the elements of the list randomly using different methods as specified above.

Using random.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. The ordering of lists is lost in this process which is the only drawback of this method.

Syntax

random.shuffle(sequence, function)

Parameters

  • sequence — any sequence like a list, tuple, etc.
  • function(optional)— a function’s name that returns a value between 0.0 and 1.0. The function random() will be used if it is not specified.

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task –.

  • Use the import keyword to import the random module.
  • Create a variable to store the input list.
  • Print the input list.
  • Use the random.shuffle() function to shuffle all the list elements randomly by passing the list as an argument to it.
  • Print the resultant shuffled list.
Читайте также:  Проверка стационарности временного ряда python

Example

The following program returns the shuffled list using random.shuffle() function–

# importing random module import random # input list inputList = [3, 10, 5, 9, 2] # Printing the input list print ("Input list: ", inputList) # shuffling the list of elements using the random module shuffle function random.shuffle(inputList) # Printing the shuffled list print ("Shuffled list: ", inputList)

Output

On executing, the above program will generate the following output –

Input list: [3, 10, 5, 9, 2] Shuffled list: [9, 3, 10, 2, 5]

Using random.sample() function

The random.sample() method in python returns a new shuffled list. The original list remains unchanged.

The random.sample() method returns a list containing a randomly selected number of elements from a sequence.

Syntax

Parameters

  • sequence — any sequence like a list, tuple, etc
  • k — number of elements to return

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task –.

  • Use the import keyword to import the random module
  • Use the random.sample() function to shuffle all the list elements randomly by passing the input list, and length of an input list using the len() function(The number of items in an object is returned by the len() method) as arguments.
  • Print the resultant shuffled list.

Example

The following program returns the shuffled list using random.shuffle() function–

# importing random module import random # input list inputList = [3, 10, 5, 9, 2] # Printing the input list print ("Input list: ", inputList) # shuffling the list elements using the sample function shuffledList = random.sample(inputList, len(inputList)) # Printing the shuffled list print ("Shuffled list: ", shuffledList)

Output

On executing, the above program will generate the following output –

Input list: [3, 10, 5, 9, 2] Shuffled list: [2, 5, 9, 10, 3]

Using Fisher-Yates shuffle Algorithm

This is a well-known algorithm in Python that is used to shuffle a sequence of numbers.

Fisher-Yates shuffle Algorithm

The Fisher-Yates shuffle Algorithm has a time complexity of O(n). The assumption is that we are given the function rand(), which generates a random number in O(1) time. The idea is to begin with the last element and swap it with a randomly chosen element from the entire array (including the last). Consider the array from 0 to n-2 (with the size reduced by one) and repeat the process until we reach the first element.

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task –.

  • Use the for loop to traverse from the end of the list with the len() function (returns the number of items in an object)
  • Get the random index till the current index value using the random.randint() method(Returns a random number within the specified range)
  • Swap the current index element with the element at a random index
  • Print the resultant shuffled list.

Example

The following program returns the shuffled list using Fisher-Yates shuffle Algorithm –

# importing random module import random # input list inputList = [3, 10, 5, 9, 2] # Printing the input list print ("Input list: ", inputList) # traversing from the end of the list(In reverse order) for p in range(len(inputList)-1, 0, -1): # getting a random index from 0 to the current index q = random.randint(0, p + 1) # Swap the current index element with the element at a random index inputList[p], inputList[q] = inputList[q], inputList[p] # Printing the shuffled list print ("Shuffled list: ", inputList)

Output

On executing, the above program will generate the following output –

Input list: [3, 10, 5, 9, 2] Shuffled list: [9, 10, 3, 5, 2]

Using random.randint() and pop() function

random.randint() − Returns a random number within the specified range

Example

The following program returns the shuffled list using random.randint() and pop() function –

# importing random module import random # input list inputList = [3, 10, 5, 9, 2] # Printing the input list print("Input list: ", inputList) # getting the list length listLength = len(inputList) # repeating the loop till the length of the list for i in range(listLength): # getting a random index in the range 0 and list Length - 1 randomIndex = random.randint(0, listLength-1) # deleting the element at that corresponding index from the list ele= inputList.pop(randomIndex) # appending the above-deleted element to the input list(adding the element at last) inputList.append(ele) # Printing the shuffled list print ("Shuffled list: ", inputList)

Output

On executing, the above program will generate the following output –

Input list: [3, 10, 5, 9, 2] Shuffled list: [10, 2, 3, 5, 9]

Conclusion

In this article, we learned four different Python methods for shuffle the given list. We also learned about the Fisher-Yates algorithm for shuffled lists and how to use it in Python.

Источник

Shuffle List in Python: 03 Different Methods (with Code)

Shuffle List in Python: 03 Different Methods (with Code)

A lottery, a lucky draw, and a card game. What do all three of these games have in common? All of them require a step to be performed. What is that step? These three games require shuffling. In various cases of programming, you will be required to shuffle a given set of items.

There is a need to shuffle a given set of items. In this article, we will learn how to shuffle a list in python. And Yes, you can do it with and without using the shuffle command.

What is a list in python?

A list in python is a data structure that provides sequential access to a collection of items. Too much technical jargon? Well, imagine that scenario that your mom is sending you out to get groceries, she will hand you some money and along with that a list.

The list will be a sequence of items that you need to buy and you can use the list to see what item to buy at any time. Similarly, in python, you can create a list that allows you to store multiple items under one name and then use that name to access all the items.

python list

There are two methods that can be used to declare a list in python, the first method is to enclose all the items that we want to include in the list inside square braces [ ].

The other method is to use the list() function to create a list. You can pass all the items that you want to include in the list inside the list() function and it will return a list with all the items.

You can also create empty lists to which you can add elements later in your code. To do this you either use empty square braces or the list() function with no arguments. Have a look at the code below to understand this further:

#Creating a list using square braces lis1 = [15,12,48,19,63] #Creating a list using list function lis2 = list((24,18,19,47)) #Creating an empty list emptylis1 = [] emptylis2 = list() print("List1: ",lis1,"\n","List2: ",lis2,"\n","EmptyLists: ",emptylis1,emptylis2)
List1: [15, 12, 48, 19, 63] List2: [24, 18, 19, 47] EmptyLists: [] []

How to shuffle a list in Python?

There are 03 methods to shuffle a list in python, Fisher-Yates Shuffle Algorithm, the shuffle method, and the sampling method. Let us discuss all of them in detail.

01) Fisher-Yates Algorithm

The Fisher-Yates Algorithm provides a technique to shuffle the items in a list by swapping the place of an item with another item from a random index in the list. An index is a number inside the memory that can be used to access elements in a list. If we have a list,

then the process to access a number say 28 would be Lis[1], where 1 is the index of 28. Indexes start at 0 from the first item in a list and go in sequential order to the last item in a list. The Fisher-Yates Algorithm uses the index to shuffle the items of the list.

The algorithm goes through a list in reverse, starting from the last index, and uses a method in python, called randint(). The randint() method generates a random integer value between the start and stops points that we provide.

In the Fisher-Yates Algorithm, the start point will be 0 and the stop point will be the length of the list minus 1 for the randint() method. The Fisher-Yates Algorithm causes the original indices of the list to be lost, so we cannot go back from shuffling the list to the original list.

The python code implementation for this is shown below:

import random lis1 = [15,12,48,19,63] print("The original list is: ",lis1) for i in range(len(lis1)-1,0,-1): j = random.randint(0,i+1) #selecting a random item's index lis1[i],lis1[j] = lis1[j],lis1[i] #swapping the two items print("The shuffled list is: ",lis1)
The original list is: [15, 12, 48, 19, 63] The shuffled list is: [15, 19, 12, 63, 48]

02) Shuffle Method

Instead of implementing an algorithm by manually coding the algorithm, you can also shuffle a list in python by using its in-built library. A library is a collection of modules or pre-defined functions that you can directly call and use in your code without worrying about its implementation.

To shuffle a list, we can use the random library and the shuffle() method that is available inside it. The shuffle method takes the list that we want to shuffle as an argument and then shuffles it in place.

This means that the shuffle method does not return anything but makes the changes on the original list itself. The original list is hence lost when we use the shuffle method.

The python code for the shuffle method is given below;

import random lis1 = [15,12,48,19,63] print("The original list is: ",lis1) random.shuffle(lis1) #shuffle method print("The shuffled list is: ",lis1)
The original list is: [15, 12, 48, 19, 63] The shuffled list is: [19, 48, 12, 63, 15]

03) Sample Method

In certain situations, we might need to keep the original list intact without disturbing its items. But we also need to shuffle the list of items. 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. In this method, we do not lose the original list and at the same time also obtain the shuffled list we require.

The code implementation for this is provided below:

import random lis1 = [15,12,48,19,63] print("The original list is: ",lis1) lis2 = random.sample(lis1,len(lis1)) print("The original list after shuffling: ",lis1) print("The shuffled list is: ",lis2)
The original list is: [15, 12, 48, 19, 63] The original list after shuffling: [15, 12, 48, 19, 63] The shuffled list is: [48, 63, 12, 15, 19]

Takeaways

Lists in python are one of the basic data structures that exist and now you know how 3 different ways to shuffle a list in python with code. You can also shuffle the list without using the shuffle command.

The Fisher-Yates Algorithm swaps two items randomly, the shuffle() method and the sample() method. The first two methods cause the original list to be lost whereas the third method preserves the original ordering of the list.

Источник

Оцените статью