l = [1, 2, 3, 4, 5, 6]
x = len(l)
last = l[x]
print(last)
I want to print last element of the list but its showing error.
l = [1, 2, 3, 4, 5, 6]
x = len(l)
last = l[x]
print(last)
I want to print last element of the list but its showing error.
Try this. You can use indexing to get the last element of the list.
l = [1, 2, 3, 4, 5, 6]
print(l[-1])
python
start counting elements at zero, so last element is len(l) minus one that is your code after repair is
l = [1, 2, 3, 4, 5, 6]
x = len(l) - 1
last = l[x]
print(last)
however you might use negative index to be more concise that is do
l = [1, 2, 3, 4, 5, 6]
last = l[-1]
print(last)
What you're doing wrong is that python indexing starts at 0 (first element = 0), and to calculate the n
th position in python, you do n
-1, so you need to do len(l) - 1
:
l = [1, 2, 3, 4, 5, 6]
x = len(l) - 1
last = l[x]
print(last) # 6
But if you use negative indexing, it starts from the end, which makes getting the last element quicker and more efficient:
x = -1
last = l[x]
print(last) # 6