How do I get last element of a list?

Given a Python list, we have to get the last element from it.
Submitted by Nijakat Khan, on July 15, 2022

There are multiple approaches to get the last element of the list. Here, we are discussing some of them.

Method 1: Using slicing

With the use of the slicing method, we can easily find the last element. The slicing method is used to read a collection from starting index to the last index here we can also define the difference between the element. We can also define starting index and last index.

Syntax:

[si : ei : [difference]]

Here, si stands for starting index and ei stands for end index and here the difference is optional. If we define –1 in the place of the difference it will return the collection in reverse form.

Example 1:

# List
list=[1,2,3,4,5,6,7,8,"Includehelp.com"]

# It will run to the one position from the last
last_elemet=list [-1]

# Prints the value of last_element
print(last_elemet)

Output:

Includehelp.com

Method 2: Using len() method

The len() function is used to get the length of a string, list, tuple, etc.

Syntax:

k=len(a)

The statement will return and store the length of a in k.

Example 2:

# List
l=["Gwalior","Delhi", "Bhopal", "Indore", "Noida", "Delhi", "Ajmer"]

print(l[len(l)-1])

Output:

Ajmer

In the above code, we have a list L then it will print the last element. It will get the length of the list and subtract one from the length of L. when we subtract one from the length of any sequence it returns the index of the last element now, we have the index of the last element now we can easily find the last element with the help of the index.

Method 3: Using pop() method

The pop() is used to remove the last element but we can also get the last element. With the use of pop() we can get the last element but we will also lose the last element from the list.

Syntax:

K = l.pop()

The statement will remove the last element from the list l and store it in K.

Example 3:

# List
l=["Gwalior","Delhi", "Bhopal", "Indore", "Noida", "Delhi", "Ajmer"]

# Removes the last element from the 
# list l and store it into k 
k=l.pop()

# Prints the last element
print(k)

# Prints the list from which last element 
# has removed
print(l)

Output:

Ajmer
['Gwalior', 'Delhi', 'Bhopal', 'Indore', 'Noida', 'Delhi']

Python List Programs »



Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.