How to Get the Last N Elements of a List in Python [7 Ways]

Have you ever needed to get the last n elements of a list in Python? But not sure which is the best way to do it. There are various methods you can use.

In this Python tutorial, I will discuss these methods in detail and provide Python code with illustrative examples for each.

Methods explained in this Python article are listed below:

  • Using list slicing
  • Using indexing
  • Using while loop
  • Using pop() method
  • Using list comprehension
  • Using islice() and reversed() methods
  • Using a generator

Get the last N elements of a list in Python using list slicing

In Python, this can be performed in 1 line rather than using a loop with the list slicing functionality.

List slicing in Python is done by the simple slicing operator, i.e., colon(:). Using the operator, you can specify where to start the slicing, where to end, and the step.

This is the complete program to get the last n elements of a list in Python using list-slicing.

number_list = [7, 5, 2, 6, 9, 13, 10]

print("The original list : " + str(number_list))
N = 5
result = number_list[-N:]
 
print("The last N elements of list are : " + str(result))

It will retrieve the last N elements from the list named number_list. In simple words, the minus operator is used to specify slicing from one end.

result = number_list[-N:]

Output:

The original list : [7, 5, 2, 6, 9, 13, 10]
The last N elements of list are : [2, 6, 9, 13, 10]

You can refer to the screenshot below to see the output of the Python code.

Get the last N elements of a list in Python

How to get last N elements of a list in Python using indexing

This is the most common method of getting the last element of a list in Python. To get the last element in a Python list, use -1 as the index value of the list.

READ:  Python program to print pattern (10 Examples)

Lists in Python are 0-indexed, which means that the first element has an index of 0, the second element has an index of 1, and so on.

To get the last n elements of a list in Python using indexing, you should use index -1. This index refers to the last element of the list.

input_list = [10, 2, 8, 4, 1]
last_element = input_list[-1]
print("The last element of the given input_list:",last_element)

Output:

The last element of the given input_list: 1

The screenshot below provides the output of the Python program to get the last N elements of a list in Python using indexing.

Python program to get the last N elements of a list

Python program to get the last N element of a list using a while loop

Using a while loop is another approach to get the last n element of a list in Python.

Below is the Python code to get the last n element of a list using a while loop.

num_list = [114, 512, 132, 166, 187, 238, 110]
print("The original list : " + str(num_list))
 
last_N_num = 3
last_num=num_list[::-1]
result=[]
i=0
while(i<last_N_num):
    result.append(last_num[i])
    i+=1
result.reverse()
print("The last N elements of list are : " + str(result))

This Python program extracts the last N elements (where N is specified by last_N_num) from the list and gives the output of the last N elements of the given list in Python.

Output:

The original list : [114, 512, 132, 166, 187, 238, 110]
The last N elements of list are : [187, 238, 110]

The screenshot below gives the output of the above program to get the last n elements of a list in Python using a while loop.

How to get the last N elements of a list in Python using  a while loop

Python program to get the last n elements of the list using the pop() method

We can use this method to get the last n element of a list in Python. The pop() method is a commonly used method in Python lists that removes and returns the last element of a list.

READ:  Python - Create Dictionary Of Tuples

Below is the program to get the last n elements of a list in Python using the pop() method.

price_list = [4456, 2781, 489, 902]
last_element = price_list.pop()

print("Last N element of the given list is:",last_element)

Output:

price_list = [4456, 2781, 489, 902]
last_element = price_list.pop()

print("Last N element of the given list is:",last_element)

Refer to the image below for the output to get the last n elements of a list in Python using the pop() method.

Get the last N elements of a list using pop() in Python

Get the last N elements of a list in Python using list comprehension

In Python, I will create a new list containing only the last elements of the input list to get the last N elements of a list using list comprehension.

Here is the complete program to get the last n elements of a list in Python using list comprehension.

input_list = [47, 1, 11, 53, 28, 22]
last_element_of_list = [x for x in input_list if x == input_list[-1]]
print("The last element of the input_list is:",last_element_of_list)

This list comprehension creates a new list by iterating over each element x in the input_list and including it in the new list only if it is equal to the last element of the input_list in Python.

Then, it filters out all elements from the input_list except its last element.

last_element_of_list = [x for x in input_list if x == input_list[-1]]

Output:

The last element of the input_list is: [22]

You can see the output of the Python program to get the last N element of a list using list comprehension.

Program to get the last N element of a lsit using list comprehension in Python

How to get the last N elements of a list using the islice() with reverse()

This is another way to get the last N elements of a list using the islice() with reverse() method in Python. Here, from the itertools module in Python, import the islice() function.

The islice function in Python can be used to get the sliced list, and reversed function is used to get the elements from the end.

READ:  How to Indent Multiple Lines in Python

Below is the code to get the last n elements of a list in Python using the islice() with reverse() methods.

from itertools import islice
N = 1
USA_state_list = ['California', 'Texas', 'Florida', 'Alska', 'Hawaii']
print("The original list : " + str(USA_state_list))

output = list(islice(reversed(USA_state_list), 0, N))
print("The last N elements of list are : " + str(output))

Here, a list named output containing the last N elements from the reversed(USA_state_list) using the islice() function from the itertools module.

Get the last elements of a list in Python using islice()

Python program to get the last n elements of a list using the generator

In Python, a generator is a function that returns an iterator that produces a sequence of values when iterated over.

Generators are useful when we want to create a Python list with a sequence of values, but we don’t want to simultaneously store all of them in the resultant list.

This is the source code to get the last n elements of a list in Python using the generator.

def get_last_num(last, n):
    yield last[len(last)-n:len(last)]
 
cities_list = ['New York', 'Chicago', 'San Deigo', 'Phoenix', 'Dallas']
print("The original list : " + str(cities_list))
 
print("The last N elements of list are : " + str(list(get_last_num(cities_list, 2))))

The generator function named get_last_num that takes two parameters. It yields a slice of the last sequence, starting from the index.

def get_last_num(last, n):
    yield last[len(last)-n:len(last)]

Output:

The original list : ['New York', 'Chicago', 'San Deigo', 'Phoenix', 'Dallas']
The last N elements of list are : [['Phoenix', 'Dallas']]

You can refer to the screenshot below to see the output.

How to get the last N elements of a list in Python using generator()

Conclusion

I have covered different approaches to get the last n elements of a list in Python. Here, I have explained seven methods with examples such as the list-slicing method, using indexing, while loop, pop() method, list comprehension, islice() with reverse methods, and generator.

I hope you like this article, as I have provided a step-by-step explanation of how to get the last N element of a list in Python.

You may also like to read: