72.1k views
4 votes
"Given that plist refers to a non-empty list ,write a statement that assigns the int -1 to the last element of the list?

A) Plist[-1] = -1.
B) Plist.append(-1).
C) Plist[len(plist) - 1] = -1.
D) Plist.insert(len(plist), -1).

1 Answer

3 votes

Final answer:

To assign the integer -1 to the last element of a non-empty Python list, use the statement Plist[-1] = -1. This method utilizes Python's negative indexing, which allows for direct access to the end of a list.

Step-by-step explanation:

The question pertains to modifying elements within a Python list. Specifically, it asks how to assign the integer -1 to the last element of a non-empty list. The correct statement to accomplish this task is option A) Plist[-1] = -1. This is because in Python, negative indices start from the end of the list, with -1 being the last element. Thus, Plist[-1] directly accesses the last element and assigns the value -1 to it.

Option B) Plist.append(-1) would add -1 as a new element at the end of the list rather than changing the existing last element. Option C) Plist[len(plist) - 1] = -1 would also work as it calculates the index of the last element using the length of the list. However, it's more verbose than option A. Lastly, option D) Plist.insert(len(plist), -1) would insert -1 after the last element, effectively also adding a new element to the end of the list, instead of replacing the last element.

User Silverfish
by
8.3k points