Python Tutorial
Python Flow Control
Python Functions
Python Data Types
Python Date and Time
Python Files
Python String
Python List
Python Dictionary
Python Variable
Python Input/Output
Python Exceptions
Python Advanced
To shuffle a list in Python, you can use the random.shuffle()
function from the random
module. This function shuffles the list in place, meaning that it modifies the original list.
Here's an example:
import random my_list = [1, 2, 3, 4, 5] random.shuffle(my_list) print(my_list)
If you want to shuffle the list without modifying the original list, you can create a copy of the list before shuffling:
import random my_list = [1, 2, 3, 4, 5] shuffled_list = my_list.copy() random.shuffle(shuffled_list) print("Original list:", my_list) print("Shuffled list:", shuffled_list)
In this example, the copy()
method is used to create a new list with the same elements as my_list
. The random.shuffle()
function then shuffles the new list, leaving the original list unchanged.
Shuffle elements in list Python:
import random my_list = [1, 2, 3, 4, 5] random.shuffle(my_list) print("Shuffled List:", my_list)
Randomize list order in Python:
import random my_list = ['apple', 'orange', 'banana', 'grape'] random.shuffle(my_list) print("Randomized List Order:", my_list)
Shuffle array in Python:
import array import random my_array = array.array('i', [1, 2, 3, 4, 5]) shuffled_array = array.array('i', random.sample(my_array, len(my_array))) print("Shuffled Array:", shuffled_array)
List shuffling algorithm in Python:
import random def custom_shuffle(lst): for i in range(len(lst) - 1, 0, -1): j = random.randint(0, i) lst[i], lst[j] = lst[j], lst[i] my_list = [1, 2, 3, 4, 5] custom_shuffle(my_list) print("Custom Shuffled List:", my_list)
How to randomize a list in Python:
import random my_list = [1, 2, 3, 4, 5] # Approach 1: Using random.shuffle() random.shuffle(my_list) print("Shuffled List (Approach 1):", my_list) # Approach 2: Using sorted() with random key randomized_list = sorted(my_list, key=lambda x: random.random()) print("Shuffled List (Approach 2):", randomized_list)
Random order list Python:
import random original_list = ['a', 'b', 'c', 'd', 'e'] random_order_list = [item for item in random.sample(original_list, len(original_list))] print("Random Order List:", random_order_list)
Shuffle list elements randomly in Python:
import random def shuffle_list_elements(lst): random.shuffle(lst) my_list = [10, 20, 30, 40, 50] shuffle_list_elements(my_list) print("Shuffled List Elements:", my_list)
Python random.shuffle() function example:
random.shuffle()
function to shuffle a list in place.import random my_list = ['x', 'y', 'z'] random.shuffle(my_list) print("Shuffled List:", my_list)
In-place list shuffling in Python:
import random def fisher_yates_shuffle(lst): for i in range(len(lst) - 1, 0, -1): j = random.randint(0, i) lst[i], lst[j] = lst[j], lst[i] my_list = [1, 2, 3, 4, 5] fisher_yates_shuffle(my_list) print("In-Place Shuffled List:", my_list)