Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

python slice last 2 items of list

# 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]
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #python #slice #items #list
ADD COMMENT
Topic
Name
4+9 =