+

Python | Slicing list from Kth element to last element

Method # 1: Use None
While slicing a list, specifying the desired first index K and specifying "None" as the second argument when slicing internally works like slicing all elements from K in the list to the end, including it.

# Python3 demo code
# slicing list from K to the end
# using None

 
# initializing list

test_list = [ 5 , 6 , 2 , 3 , 9 ]

  
# print the original list

print ( " The original list is: " + str (test_list) )

 
# index to start slicing

K = 2

 
# using None
# slice the list from K to the end

res = test_list [K : None ]

  
# print result

print ( "The sliced ​​list is:" +   str (res))

Exit:

 The original list is: [5, 6, 2, 3, 9] The sliced ​​list is: [2, 3, 9] 

Method # 2: Leaving the last item empty
Normally, by not specifying any element as the final slicing element, Python instructs to include the entire list after the K in the list. But the main disadvantage in using this — readability of the code. Hence, the above method is preferred over this one.

# Python3 demo code
# list slicing from K to the end
# without specifying the last element

 
# initializing list

test_list = [ 5 , 6 , 2 , 3 , 9 ]

 
# print original list

print ( " The original list is: " + str (test_list))

 
# index to start slicing

K = 2

  
# without specifying the last element
# slice the list from K to the end

res = test_list [K:]

  
# print result

print ( " The sliced ​​list is: " +   str (res))

Exit:

 The original list is: [5, 6, 2, 3, 9] The sliced ​​list is: [2, 3, 9] 
Get Solution for free from DataCamp guru