197k views
1 vote
Use list indexing to print the last element of the list literal value.

Note: Do not store the list value into a temporary variable. The goal is to practice indexing a list literal, to show that it is possible.
Given:
print(["Not me", "Nor me", "Print me!"])
Do in python

1 Answer

5 votes

Answer:

print(["Not me", "Nor me", "Print me!"][2])

Step-by-step explanation:

Given

print(["Not me", "Nor me", "Print me!"])

Required

Print last element of the list literal value

The implication of this question is to print "Print me!"

We start by analysing the given list.

The given list has 3 elements

But because indexing of a list starts from 0, the index of the last element will be 3 - 1 = 2

So, to print the last element, we simply direct the print statement to the last index.

This is done as follows

print(["Not me", "Nor me", "Print me!"][2])

The [2] shows that only the literal at the last index will be printed.

This means that the string "Print me!" will be printed.

The code can also be rewritten as follows

mylist = ["Not me", "Nor me", "Print me!"]

print(mylist[2])

Here, the first line stores the list in a variable.

The second line prints the last element of the list literal value which is "Print me!"

User Pazonec
by
4.0k points