1

I am basically writing a code to take a list as an input and output the last item of the user given list items. This is the entire code:

     input_list = [1, 2, 3, 4, 5, 6]
     list_Length = int(input())

     for i in range(list_Length):
         user_input = input()
         input_list.append(user_input)

     last_Before = list_Length - 2
     print(last_Before)
     print(input_list[: last_Before: -1])

My question is, instead of writing print(input_list[: last_Before: -1]) at the last line, if I write print(input_list[0: last_Before: -1]), it gives me an empty string. WHY??!?!

Prasad Darshana
  • 186
  • 2
  • 14
Villicus
  • 9
  • 2

1 Answers1

0

That would be because the -1 in input_list[::-1] means that the list is going to be iterated in reverse order. If you write input_list[0:last_Before:-1] that means go from 0 to last_Before by subtracting -1 which prints an empty list since 0-1 = -1 and you cannot reach last_Before therefore, it prints an empty list. When you write input_list[:last_Before:-1] it prints the last element where the first index is implicitly last_Before+1. If you try printing input_list[last_Before+1:last_Before:-1] then it will print the same as input_list[:last_Before:-1].

CompEng007
  • 86
  • 8