Python array last index

6 ways to get the last element of a list in Python

In this article, we will discuss six different ways to get the last element of a list in python.

Get last item of a list using negative indexing

List in python supports negative indexing. So, if we have a list of size “S”, then to access the Nth element from last we can use the index “-N”. Let’s understand by an example,
Suppose we have a list of size 10,

sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]

To access the last element i.e. element at index 9 we can use the index -1,

# Get last element by accessing element at index -1 last_elem = sample_list[-1] print('Last Element: ', last_elem)

Similarly, to access the second last element i.e. at index 8 we can use the index -2.

Читайте также:  Css horizontal touch scroll

Frequently Asked:

Using negative indexing, you can select elements from the end of list, it is a very efficient solution even if you list is of very large size. Also, this is the most simplest and most used solution to get the last element of list. Let’s discuss some other ways,

Get last item of a list using list.pop()

In python, list class provides a function pop(),

It accepts an optional argument i.e. an index position and removes the item at the given index position and returns that. Whereas, if no argument is provided in the pop() function, then the default value of index is considered as -1. It means if the pop() function is called without any argument then it removes the last item of list and returns that.

Let’s use this to remove and get the last item of the list,

sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # Remove and returns the last item of list last_elem = sample_list.pop() print('Last Element: ', last_elem)

The main difference between this approach and previous one is that, in addition to returning the last element of list, it also removes that from the list.

Get last item of a list by slicing

We can slice the end of list and then select first item from it,

sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # Get a Slice of list, that contains only last item and select that item last_elem = sample_list[-1:][0] print('Last Element: ', last_elem)

We created a slice of list that contains only the last item of list and then we selected the first item from that sliced list. It gives us the last item of list. Although it is the most inefficient approach, it is always good to know different options.

Get last item of a list using itemgetter

Python’s operator module provides a function,

It returns a callable object that fetches items from its operand using the operand’s __getitem__() method. Let’s use this to get the last item of list by passing list as an operand and index position -1 as item to be fetched.

import operator sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] last_elem = operator.itemgetter(-1)(sample_list) print('Last Element: ', last_elem)

It gives us the last item of list.

Get last item of a list through Reverse Iterator

In this solution we are going to use two built-in functions,

  1. reversed() function : It accepts a sequence and returns a Reverse Iterator of that sequence.
  2. next() function: It accepts an iterator and returns the next item from the iterator.

So, let’s use both the reversed() and next() function to get the last item of a list,

sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # get Reverse Iterator and fetch first element from reverse direction last_elem = next(reversed(sample_list), None) print('Last Element: ', last_elem)

It gives us the last item of list.
How did it work?
By calling the reversed() function we got a Reverse Iterator and then we passed this Reverse Iterator to the next() function. Which returned the next item from the iterator.
As it was a Reverse Iterator of our list sequence, so it returned the first item in reverse order i.e. last element of the list.

Get last item of a list by indexing

As the indexing in a list starts from 0th index. So, if our list is of size S, then we can get the last element of list by selecting item at index position S-1.
Let’s understand this by an example,

sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # get element at index position size-1 last_elem = sample_list[len(sample_list) - 1] print('Last Element: ', last_elem)

It gives us the last item of list.

Using the len() function we got the size of the list and then by selecting the item at index position size-1, we fetched the last item of the list.

So, here we discussed 6 different ways to fetch the last element of a list, although first solution is the simplest, efficient and most used solution. But it is always good to know other options, it gives you exposure to different features of language. It might be possible that in future, you might encounter any situation where you need to use something else, like in 2nd example we deleted the last element too after fetching its value.

The Complete example is as follows,

import operator def main(): print('*** Get last item of a list using negative indexing ***') sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # Get last element by accessing element at index -1 last_elem = sample_list[-1] print('Last Element: ', last_elem) print('*** Get last item of a list using list.pop() ***') sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # Remove and returns the last item of list last_elem = sample_list.pop() print('Last Element: ', last_elem) print('*** Get last item of a list by slicing ***') sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] last_elem = sample_list[-1:][0] print('Last Element: ', last_elem) print('*** Get last item of a list using itemgetter ***') sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] last_elem = operator.itemgetter(-1)(sample_list) print('Last Element: ', last_elem) print('*** Get last item of a list through Reverse Iterator ***') sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # get Reverse Iterator and fetch first element from reverse direction last_elem = next(reversed(sample_list), None) print('Last Element: ', last_elem) print("*** Get last item of a list by indexing ***") sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # get element at index position size-1 last_elem = sample_list[len(sample_list) - 1] print('Last Element: ', last_elem) if __name__ == '__main__': main()
*** Get last item of a list using negative indexing *** Last Element: 9 *** Get last item of a list using list.pop() *** Last Element: 9 *** Get last item of a list by slicing *** Last Element: 9 *** Get last item of a list using itemgetter *** Last Element: 9 *** Get last item of a list through Reverse Iterator *** Last Element: 9 *** Get last item of a list by indexing *** Last Element: 9

Источник

Python array last index

Last updated: Feb 20, 2023
Reading time · 4 min

banner

# Table of Contents

# Detect the last item in a list using a for loop in Python

To detect the last item in a list using a for loop:

  1. Use the enumerate function to get tuples of the index and the item.
  2. Use a for loop to iterate over the enumerate object.
  3. If the current index is equal to the list’s length minus 1 , then it’s the last item in the list.
Copied!
my_list = ['one', 'two', 'three', 'four'] for index, item in enumerate(my_list): if index != len(my_list) - 1: print(item, 'is NOT last in the list ✅') else: print(item, 'is last in the list ❌')

detect last item in list using for loop

We used the enumerate() function to get an enumerate object we can iterate over.

The enumerate function takes an iterable and returns an enumerate object containing tuples where the first element is the index and the second is the item.

Copied!
my_list = ['one', 'two', 'three', 'four'] # 👇️ [(0, 'one'), (1, 'two'), (2, 'three'), (3, 'four')] print(list(enumerate(my_list)))

We used a for loop to iterate over the enumerate object and on each iteration, we check if the current index is NOT equal to the last index in the list.

# Checking if the current index is equal to the last index

If the current index is not equal to the last index in the list, then the element is not the last list item.

Copied!
my_list = ['one', 'two', 'three', 'four'] for index, item in enumerate(my_list): if index != len(my_list) - 1: print(item, 'is NOT last in the list ✅') else: print(item, 'is last in the list ❌')

check if current index is equal to last index

Python indexes are zero-based, so the first index in a list is 0 , and the last index is len(my_list) — 1 .

# Checking if we are on the last iteration of the loop

If you need to check if the element is the last list item, change the not equals (!=) operator to the equals (==) operator.

Copied!
my_list = ['one', 'two', 'three', 'four'] for index, item in enumerate(my_list): if index == len(my_list) - 1: print(item, 'is last in the list ✅') else: print(item, 'is NOT last in the list ❌')

check if we are on the last iteration of the loop

The example checks if the current index is equal to the last index in the list.

# Not performing an operation for the Last item in the List

If you don’t want to perform an operation for the last item in the list, use a list slice that excludes it.

Copied!
my_list = ['one', 'two', 'three', 'four'] for item in my_list[:-1]: print(item, 'is NOT last in the list ✅') print(my_list[-1], 'is last in the list ❌')

not performing an operation for the last item in the list

The my_list[:-1] syntax returns a slice of the list that excludes the last element.

The syntax for list slicing is my_list[start:stop:step] .

The slice in the example starts at index 0 and goes up to, but not including the last item in the list.

Negative indices can be used to count backward, e.g. my_list[-1] returns the last item in the list and my_list[-2] returns the second-to-last item.

# Joining without a separator after the last item

If you need to join the items in the list with a string separator, but don’t want to add the separator after the last element, use the str.join() method.

Copied!
my_list = ['one', 'two', 'three', 'four'] result_1 = '_'.join(my_list) print(result_1) # 👉️ 'one_two_three_four' result_2 = ' '.join(my_list) print(result_2) # 👉️ 'one two three four'

join without separator after last item

The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

If your list contains numbers or other types, convert all of the values to string before calling join() .

Copied!
my_list = ['one', 1, 'two', 2, 'three', 3] list_of_strings = list(map(str, my_list)) result_1 = '_'.join(list_of_strings) print(result_1) # 👉️ 'one_1_two_2_three_3' result_2 = ' '.join(list_of_strings) print(result_2) # 👉️ 'one 1 two 2 three 3'

The string the method is called on is used as the separator between the elements.

If you don’t need a separator and just want to join the iterable’s elements into a string, call the join() method on an empty string.

Copied!
my_list = ['one', 'two', 'three'] result_1 = ''.join(my_list) print(result_1) # 👉️ 'onetwothree'

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью