Python list[-1] Explained: Negative Indexing, Slicing and range() Rules

Programming2 min read
Python negative indexing: list[-1] and slicing examples
On this page

In Python, list[-1] returns the last element of a list. Negative indexes count from the end: -1 is the last item, -2 the second to last, and so on. The same rule works for strings, tuples and other sequences.

nums = [10, 20, 30, 40, 50]
nums[0]     # 10  first
nums[-1]    # 50  last
nums[-2]    # 40  second to last

How negative indexes map

Positive index01234
Value1020304050
Negative index-5-4-3-2-1

Python simply adds the length: nums[-1] is nums[len(nums) - 1]. An index beyond the start, such as nums[-6] here, raises IndexError, and so does [][-1] on an empty list.

Slicing with negative numbers

Slices use [start:stop:step], where stop is not included:

nums[-2:]      # [40, 50]          last two
nums[:-1]      # [10, 20, 30, 40]  everything except the last
nums[-3:-1]    # [30, 40]
nums[::-1]     # [50, 40, 30, 20, 10]  reversed copy
nums[::2]      # [10, 30, 50]      every second item

Slices never raise IndexError; out-of-range slices just return fewer items or an empty list.

range() and the “exclusive end” rule

range(start, stop) works like slicing: start is included, stop is not.

list(range(5))         # [0, 1, 2, 3, 4]
list(range(1, 4))      # [1, 2, 3]
list(range(10, 0, -2)) # [10, 8, 6, 4, 2]
for i in range(len(nums)):
    print(i, nums[i])

To include the end value, use range(1, n + 1). Usually it is cleaner to loop directly or with enumerate:

for i, value in enumerate(nums):
    print(i, value)

Common mistakes

MistakeFix
Expecting range(1, 10) to include 10Use range(1, 11)
Off-by-one with nums[len(nums)]The last index is len(nums) - 1, or just nums[-1]
nums[-1] on an empty listCheck if nums: first
Modifying a list while looping over itLoop over a copy: for x in nums[:]

Frequently asked questions

What does [-1] mean in Python?

The last element of a sequence such as a list, string or tuple.

How do I get the last 3 items of a list?

Use the slice nums[-3:].

How do I reverse a list in Python?

nums[::-1] returns a reversed copy; nums.reverse() reverses the list in place.

Is range() inclusive or exclusive in Python?

The start is inclusive and the stop is exclusive: range(1, 4) gives 1, 2, 3.

Does negative indexing work on strings?

Yes. “hello”[-1] returns “o”.

Learn Python for security and automation

Python is the language of most security tooling and automation. Explore our courses to go from Python basics to writing your own tools.

Written by

Taifun Mamedov

Founder and instructor at Ocsaly Academy.

Courses by Taifun Mamedov

Share this article