a) Explain the use of random.choice() and random.shuffle() functions with lists using suitable examples. b) Show that lists are mutable with an example.

a) Use of random.choice() and random.shuffle() with Lists

1. random.choice()

The random.choice() function returns a random element from a non-empty list.

Example:

import random

fruits = [‘apple’, ‘banana’, ‘cherry’, ‘mango’]
random_fruit = random.choice(fruits)
print(“Randomly selected fruit:”, random_fruit)

Output (Sample): Randomly selected fruit: cherry

The output may vary each time the program is run, as the selection is random.

2. random.shuffle()

The random.shuffle() function shuffles the elements of a list in place, meaning it modifies the original list by rearranging the elements randomly.

Example:

import random

numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(“Shuffled list:”, numbers)

Output (Sample): Shuffled list: [3, 5, 1, 2, 4]

Each run may produce a different order of elements.

b) Lists are Mutable

In Python, lists are mutable, meaning their contents can be changed after creation (i.e., elements can be modified, added, or removed).

Example:

numbers = [10, 20, 30, 40]
print(“Original list:”, numbers)

Modifying the second element

numbers[1] = 99
print(“Modified list:”, numbers)





Output:

This example demonstrates that list elements can be changed, confirming that lists are mutable.

Leave a Reply

Your email address will not be published. Required fields are marked *