Basic python-5(QNA)

Q1: What do you understand by mutability? What does “in place” task mean?
A1: Mutability refers to the capability of an object (like a list or dictionary in Python) to be changed after it is created. If an object can be changed, then it is called mutable. Conversely, if an object cannot be changed, it is called immutable (like strings or tuples in Python). An “in place” task means that the operation modifies the data structure directly, without creating a new copy. This can be more efficient in terms of memory usage, especially for large data structures, because it doesn’t require extra space to hold a second copy of the data structure.
Q2: Start with the list [8,9,10]. Do the following: (a) Set the second entry (index 1) to 17 (b) Add 4, 5 and 6 to the end of the list (c) Remove the first entry from the list (d) Sort the list (e) Double the list (f) Insert 25 at index 3
A2: Here is a simple Python script that accomplishes this:
                # Start with the list
                my_list = [8, 9, 10]

                # (a) Set the second entry (index 1) to 17
                my_list[1] = 17

                # (b) Add 4, 5, and 6 to the end of the list
                my_list.extend([4, 5, 6])

                # (c) Remove the first entry from the list
                my_list.pop(0)

                # (d) Sort the list
                my_list.sort()

                # (e) Double the list
                my_list *= 2

                # (f) Insert 25 at index 3
                my_list.insert(3, 25)
                

Leave a Comment

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

Scroll to Top