python slice last 2 items of list

PHOTO EMBED

Tue Dec 13 2022 06:11:33 GMT+0000 (Coordinated Universal Time)

Saved by @tofufu #python

# Last two items of ENTIRE list
ls = [1, 2, 3, 4, 5, 6, 7, 8]
print(ls[-2:])
# [7, 8]
# equivalent to ls[len(ls)-2:len(ls)], see below

# Last two items of A PART of list
cutoff = 5
print(ls[cutoff-2:cutoff])	# where -2 is last 2 values
# [4, 5]

# Using a for loop
for i in range(0, len(ls)):
   if i+1 ==  len(ls)):
      print(ls[i-1:len(ls)])
# [7, 8]



# Negative numbers in slices are simply evaluated by adding `len(ls)`, so this is the same as `ls[len(ls) - 2:]`. For more information on slices, refer to the [Python tutorial](http://docs.python.org/tutorial/introduction.html#strings) or [this excellent stackoverflow answer](https://stackoverflow.com/a/509295/35070).
content_copyCOPY

https://stackoverflow.com/questions/11932776/how-do-i-extract-the-last-two-items-from-the-list-strings-or-tuples-in-python/11932801#11932801