Monday 20 September 2021

Python: Get last n elements from a list

Approach 1: Using plain iteration.

 

last_n_elements_1.py

def last_n_elements(my_list, n):
    temp_list = []
    size_of_list = len(my_list)
    end_index = size_of_list - n

    for i in range(end_index, size_of_list):
        temp_list.append(my_list[i])
    
    return temp_list

list1 = [2, 3, 4, 5, 7, 11, 13, 17]
first_4_elements = last_n_elements(list1, 4)

print("list1 -> ", list1)
print("last_4_elements -> ", first_4_elements)

 

Output

list1 ->  [2, 3, 4, 5, 7, 11, 13, 17]
last_4_elements ->  [7, 11, 13, 17]

 

Approach 2: using range selection.

 

last_n_elements_2.py

def last_n_elements(my_list, n):
    size_of_list = len(my_list)
    start_index = size_of_list - n
    return my_list[start_index:size_of_list]

list1 = [2, 3, 4, 5, 7, 11, 13, 17]
first_4_elements = last_n_elements(list1, 4)

print("list1 -> ", list1)
print("last_4_elements -> ", first_4_elements)

 

Output

list1 ->  [2, 3, 4, 5, 7, 11, 13, 17]
last_4_elements ->  [7, 11, 13, 17]

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment