Python: Shuffle and print a specified list
Shuffle List
Write a Python program to shuffle and print a specified list.
Visual Presentation:
Sample Solution:
Python Code:
# Import the 'shuffle' function from the 'random' module, which is used for shuffling the elements in a list
from random import shuffle
# Create a list 'color' with several color strings
color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
# Use the 'shuffle' function to randomly reorder the elements in the 'color' list
shuffle(color)
# Print the shuffled 'color' list, which will have its elements in a random order
print(color)
Sample Output:
['Yellow', 'Pink', 'Green', 'Red', 'Black', 'White']
Explanation:
In the above exercise -
color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow'] -> A list named color is defined and initialized with six string elements.
shuffle(color) -> Here the shuffle() function from the random module is called with the color list as its argument. This function shuffles the elements of the list in-place, i.e., it modifies the list directly without returning a new list.
print(color) -> Finally print() function prints the shuffled color list.
Flowchart:
Python Code Editor:
Previous: Write a Python program to print the numbers of a specified list after removing even numbers from it.
Next: Write a Python program to generate and print a list of first and last 5 elements where the values are square of numbers between 1 and 30 (both included).
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics