66.6k views
3 votes
Write a program that firstly creates a list and initializes it with the following numbers: 15,20,5,40,50,70,35,80,95 Then, it performs the following tasks - (1) modify the first element to 1 using the corresponding positive index, and modify the last element to 0 using the corresponding negative index. (2) use the append(item) method to add element 55 to the end of the list nums. - (3) delete the third element of list nums using the del statement. - (4) use the in operator to detect if 40 is in list nums. If detected (implemented with decision structure), remove it using the remove(item) method. - (5) use the index(item) method to get the index number of element 50 , then insert 90 in front of 50 using the insert(index, item) method. - (6) Sort list nums in ascending order with the sort0 method. Originat list: [15,20,5,40,50,70,35,80,95] After modification [1,20,5,40,50,70,35,80,0] After append: [1,20,5,40,50,70,35,80,0,55] After deletion: [1,20,40,50,70,35,80,0,55] After removat. an in 70 an on n ह51 After insertion [1,20,90,50,70,30,80,0,55] After sort [0,1,20,35,50,55,70,80,90]

User Gpampara
by
8.1k points

1 Answer

3 votes

Final answer:

A Python program is provided to modify a list of integers through various operations including updating elements, appending, deleting, removing, inserting, and sorting to achieve the desired final list.

Step-by-step explanation:

To accomplish the tasks requested by the student using Python, we need to follow a series of steps to modify the list according to the instructions. Here is a Python program that outputs the requested operations:

nums = [15,20,5,40,50,70,35,80,95]

# Task 1: Modify the first and last element
nums[0] = 1
nums[-1] = 0

# Task 2: Append 55 to the end
nums.append(55)

# Task 3: Delete the third element
del nums[2]

# Task 4: Remove 40 if it's in the list
if 40 in nums:
nums.remove(40)

# Task 5: Insert 90 in front of 50
index_of_50 = nums.index(50)
nums.insert(index_of_50, 90)

# Task 6: Sort the list
nums.sort()

Following these steps, the final sorted list is [0, 1, 20, 35, 50, 55, 70, 80, 90].

User Yogesh D
by
8.0k points