-1

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.

  • 2
    l[x-1] will print last element. Len returns 6, but index starts from 0 – Adelina Dec 29 '22 at 14:06
  • 1
    Does this answer your question? [How do I get the last element of a list?](https://stackoverflow.com/questions/930397/how-do-i-get-the-last-element-of-a-list) – EEtch Dec 29 '22 at 14:40

3 Answers3

0

Try this. You can use indexing to get the last element of the list.

l = [1, 2, 3, 4, 5, 6]
print(l[-1])
Ikram Khan Niazi
  • 789
  • 6
  • 17
0

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)
Daweo
  • 31,313
  • 3
  • 12
  • 25
0

What you're doing wrong is that python indexing starts at 0 (first element = 0), and to calculate the nth 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
Pythoneer
  • 319
  • 1
  • 16