w3resource

Python: Shuffle and print a specified list

Python List: Exercise - 15 with Solution

Write a Python program to shuffle and print a specified list.

Visual Presentation:

Python: Shuffle and print a specified list

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:

Flowchart: Shuffle and print a specified list

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/list/python-data-type-list-exercise-15.php