Как найти последний элемент списка питон

In Python, how do you get the last element of a list?

To just get the last element,

  • without modifying the list, and
  • assuming you know the list has a last element (i.e. it is nonempty)

pass -1 to the subscript notation:

>>> a_list = ['zero', 'one', 'two', 'three']
>>> a_list[-1]
'three'

Explanation

Indexes and slices can take negative integers as arguments.

I have modified an example from the documentation to indicate which item in a sequence each index references, in this case, in the string "Python", -1 references the last element, the character, 'n':

 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
   0   1   2   3   4   5 
  -6  -5  -4  -3  -2  -1

>>> p = 'Python'
>>> p[-1]
'n'

Assignment via iterable unpacking

This method may unnecessarily materialize a second list for the purposes of just getting the last element, but for the sake of completeness (and since it supports any iterable — not just lists):

>>> *head, last = a_list
>>> last
'three'

The variable name, head is bound to the unnecessary newly created list:

>>> head
['zero', 'one', 'two']

If you intend to do nothing with that list, this would be more apropos:

*_, last = a_list

Or, really, if you know it’s a list (or at least accepts subscript notation):

last = a_list[-1]

In a function

A commenter said:

I wish Python had a function for first() and last() like Lisp does… it would get rid of a lot of unnecessary lambda functions.

These would be quite simple to define:

def last(a_list):
    return a_list[-1]

def first(a_list):
    return a_list[0]

Or use operator.itemgetter:

>>> import operator
>>> last = operator.itemgetter(-1)
>>> first = operator.itemgetter(0)

In either case:

>>> last(a_list)
'three'
>>> first(a_list)
'zero'

Special cases

If you’re doing something more complicated, you may find it more performant to get the last element in slightly different ways.

If you’re new to programming, you should avoid this section, because it couples otherwise semantically different parts of algorithms together. If you change your algorithm in one place, it may have an unintended impact on another line of code.

I try to provide caveats and conditions as completely as I can, but I may have missed something. Please comment if you think I’m leaving a caveat out.

Slicing

A slice of a list returns a new list — so we can slice from -1 to the end if we are going to want the element in a new list:

>>> a_slice = a_list[-1:]
>>> a_slice
['three']

This has the upside of not failing if the list is empty:

>>> empty_list = []
>>> tail = empty_list[-1:]
>>> if tail:
...     do_something(tail)

Whereas attempting to access by index raises an IndexError which would need to be handled:

>>> empty_list[-1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

But again, slicing for this purpose should only be done if you need:

  • a new list created
  • and the new list to be empty if the prior list was empty.

for loops

As a feature of Python, there is no inner scoping in a for loop.

If you’re performing a complete iteration over the list already, the last element will still be referenced by the variable name assigned in the loop:

>>> def do_something(arg): pass
>>> for item in a_list:
...     do_something(item)
...     
>>> item
'three'

This is not semantically the last thing in the list. This is semantically the last thing that the name, item, was bound to.

>>> def do_something(arg): raise Exception
>>> for item in a_list:
...     do_something(item)
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 1, in do_something
Exception
>>> item
'zero'

Thus this should only be used to get the last element if you

  • are already looping, and
  • you know the loop will finish (not break or exit due to errors), otherwise it will point to the last element referenced by the loop.

Getting and removing it

We can also mutate our original list by removing and returning the last element:

>>> a_list.pop(-1)
'three'
>>> a_list
['zero', 'one', 'two']

But now the original list is modified.

(-1 is actually the default argument, so list.pop can be used without an index argument):

>>> a_list.pop()
'two'

Only do this if

  • you know the list has elements in it, or are prepared to handle the exception if it is empty, and
  • you do intend to remove the last element from the list, treating it like a stack.

These are valid use-cases, but not very common.

Saving the rest of the reverse for later:

I don’t know why you’d do it, but for completeness, since reversed returns an iterator (which supports the iterator protocol) you can pass its result to next:

>>> next(reversed([1,2,3]))
3

So it’s like doing the reverse of this:

>>> next(iter([1,2,3]))
1

But I can’t think of a good reason to do this, unless you’ll need the rest of the reverse iterator later, which would probably look more like this:

reverse_iterator = reversed([1,2,3])
last_element = next(reverse_iterator)

use_later = list(reverse_iterator)

and now:

>>> use_later
[2, 1]
>>> last_element
3

Getting the last element of the list is tricky while tracking each element, here we will discuss multiple methods to get the last element of the list. So we have given a list n, Our task is to get the last element of the list.

Example:

Input: [1, 2, 3, 4, 5, 5]
Output: 5

Input: ["Hello", "World"]
Output: World

Approaches to get the last element of list:

  • Using Reverse Iterator
  • Using negative indexing
  • Using list.pop()
  • Using reversed() + next() 
  • Using slicing
  • Using itemgetter

Using Reverse Iterator to get the last item of a list

To get the last element of the list using the naive method in Python. There can be 2-naive methods to get the last element of the list. 

  • Iterating the whole list and getting, the second last element.
  • Reversing the list and printing the first element.

Python3

test_list = [1, 4, 5, 6, 3, 5]

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

for i in range(0, len(test_list)):

    if i == (len(test_list)-1):

        print("The last element of list using loop : "

              + str(test_list[i]))

test_list.reverse()

print("The last element of list using reverse : "

      + str(test_list[0]))

Output :

The original list is : [1, 4, 5, 6, 3, 5]
The last element of list using loop : 5
The last element of list using reverse : 5

Using Negative Indexing to get the last element of list

To get last element of the list using the [] operator, the last element can be assessed easily if no. of elements in the list are already known. There is 2 indexing in Python that points to the last element in the list.

  • list[ len – 1 ] : This statement returns the last index if the list.
  • list[-1] : Negative indexing starts from the end.

Python3

test_list = [1, 4, 5, 6, 3, 5]

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

print("The last element using [ len -1 ] is : "

      + str(test_list[len(test_list) - 1]))

print("The last element using [ -1 ] is : "

      + str(test_list[-1]))

Output :

The original list is : [1, 4, 5, 6, 3, 5]
The last element using [ len -1 ] is : 5
The last element using [ -1 ] is : 5

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

To get the last element of the list using list.pop(), the list.pop() method is used to access the last element of the list. The drawback of this approach is that it also deletes the list’s last element, hence is only encouraged to use when the list is not to be reused. 

Python3

test_list = [1, 4, 5, 6, 3, 5]

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

print("The last element using pop() is : "

      + str(test_list.pop()))

Output :

The original list is : [1, 4, 5, 6, 3, 5]
The last element using pop() is : 5

Get the last item of a list using reversed() + next() 

To get the last element of the list using reversed() + next(), the reversed() coupled with next() can easily be used to get the last element, as, like one of the naive methods, the reversed method returns the reversed ordering of list as an iterator, and next() method prints the next element, in this case, last element. 

Python3

test_list = [1, 4, 5, 6, 3, 5]

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

print("The last element using reversed() + next() is : "

      + str(next(reversed(test_list))))

Output :

The original list is : [1, 4, 5, 6, 3, 5]
The last element using reversed() + next() is : 5

Get the last item of a list by slicing

In this example, we will use list slicing to get the last element from the list.

Python3

test_list = [1, 4, 5, 6, 3, 5]

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

li = last_elem = test_list[-1:][0]

print("The last element using slicing is : ", li)

Output:

The original list is : [1, 4, 5, 6, 3, 5]
The last element using slicing is :  5

Get the last item of a list using itemgetter

The itemgetter can be used instead of lambda functions.  In terms of performance over time, itemgetter is better than lambda functions. When accessing many values, it appears more concise than lambda functions. Here, we will use itemgetter to get out the last element in the list.

Python3

import operator

test_list = [1, 4, 5, 6, 3, 5]

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

li = last_elem = operator.itemgetter(-1)(test_list)

print("The last element using itemgetter is : ", li)

Output:

The original list is : [1, 4, 5, 6, 3, 5]
The last element using itemgetter is :  5

Using deque from the collections module:

Algorithm:

  1. Convert the given list to a deque object.
  2. Use the pop() method to remove and return the last element of the deque object.
  3. Return the popped element as the result.

Python3

from collections import deque

test_list = [1, 4, 5, 6, 3, 5]

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

last_elem = deque(test_list).pop()

print("The last element using deque is : " + str(last_elem))

Output

The original list is : [1, 4, 5, 6, 3, 5]
The last element using deque is : 5

Complexity Analysis: The above code returns the last element of the given list using the deque.pop() method from the collections module. The time complexity of this approach is O(1) since the pop() operation on deque takes constant time, and the space complexity is O(n) since the deque object is created to store the list elements.

Last Updated :
22 Apr, 2023

Like Article

Save Article

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,

Advertisements

# Get last element by accessing element at index -1
last_elem = sample_list[-1]

print('Last Element: ', last_elem)

Output:

Last Element:  9

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

Frequently Asked:

  • Python : How to add an element in list ? | append() vs extend()
  • Convert a list of tuples to a list in Python
  • Check if all elements in List are unique in Python
  • Convert a list to a comma-separated string in Python
last_elem = sample_list[-2]

Output:

Last Element:  8

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(),

list.pop(index)

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.

Latest Python — Video Tutorial

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)

Output:

Last Element:  9

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)

Output:

Last Element:  9

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,

operator.itemgetter(item)

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)

Output:

Last Element:  9

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)

Output:

Last Element:  9

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)

Output:

Last Element:  9

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.

Happy Coding.

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()

Output:

*** 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

Introduction

In this tutorial, we’ll take a look at some of the most common ways to find the last element in a list in Python. First, we will cover the simplest and most Pythonic way and then show some other alternative solutions afterward.

Let’s take a look at the list that we will be using:

exampleList = [1, 2, "Three", ["Four", 5], 6]

Note: A list in Python is a collection of elements that are not necessarily the same type. One list can contain elements that are numbers, strings, nested lists, etc.

How to Get the Last Element in a Python List

There’s several ways we can go about getting the last element of a list in Python — some of which are more intuitive and practical than others, and some of which actually change the original list in-place.

Winner Solution — Using Negative Indexing

Python supports the notion of negative indexing as the method of accessing list elements. This means that we can access elements in the reversed order by using the [] operator.

It’s well known how indexing in lists works:

firstElement = exampleList[0]
nthElement = exampleList[n-1]
...

The first element has the index of 0, the second has the index of 1, and the nth element has an index of n-1.

The negative indexing follows the same logic, but in reversed order. The last element has the index of -1, the second to last element has the index of -2, and so on:

lastElement = exampleList[-1]
print("Last element: ", lastElement)

print("exampleList: ", exampleList)

secondToLast = exampleList[-2]
print("Second to last element: ", secondToLast)

Which outputs:

Last element:  6
exampleList:  [1, 2, 'Three', ['Four', 5], 6]
Second to last element:  ['Four', 5]

Negative indexing does not change the original list. It is only a way of accessing elements without any changes to the original list.

This is by far the simplest and most Pythonic solution, favored by most.

Using Indexing

Simple indexing is usually used to access elements in a list in the original order using the [] operator. As described above, the first element has an index of 0, the second element has an index of 1, and so on. Knowing that, we can conclude that the last element has the index of len(exampleList)-1:

lastElement = exampleList[len(exampleList)-1]
print("Last element: ", lastElement)

print("exampleList: ", exampleList)

secondToLast = exampleList[len(exampleList)-2]
print("Second to last element: ", secondToLast)

Which outputs:

Last element:  6
exampleList:  [1, 2, 'Three', ['Four', 5], 6]
Second to last element:  ['Four', 5]

As well as negative indexing, the indexing method is only used to access elements of the list without performing any changes to the original list.

Using the pop() Method

In Python, the pop() method is used to remove the last element of the given list and return the removed item.

The pop() method can optionally accept an integer argument. It is the index of the element that we want to remove, so if we call exampleList.pop(0), the first element will be removed and returned.

If the argument is the negative number, the logic of the negative indexing will be performed to determine which element to remove. Calling exampleList.pop(-1) will result in removing the last element of the examleList.

Though, since the pop() method by default already pops the last element, there’s no real need to use indexing at all:

lastElement = exampleList.pop()
print("Last element: ", lastElement)

print("exampleList: ", exampleList)

Which outputs:

Last element:  6
exampleList:  [1, 2, 'Three', ['Four', 5]]

Note that the pop() method, by definition, does change the original list by removing the popped element.

Using Slicing

In Python, the slicing notation is used to get a sublist of a list. The notation itself is pretty simple:

exampleList[startIndex:[endIndex[:indexStep]]]

This means that we can get the sublist of the exampleList with indices starting from startIndex, all the way to the endIndex with the step of indexStep.

The endIndex and indexStep are optional arguments. If we leave the endIndex blank, its default value is the end of the original list. The default value for indexStep is 1.

If we have a list letters=['a', 'b', 'c', 'd', 'e'] and slice it using letters[1:3] the resulting sublist will be ['b', 'c', 'd']. This means that we are choosing elements of the list letters with indices 1, 2, and 3.

letters[0:4:2] will return a sublist containing only elements on the even indices — 0, 2, 4.

The key feature of the slicing notation that we will be using is that it supports negative indexing.

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

This means that letters[-1:] can be interpreted as: get all elements in list letters, from the last element to the end of list letters. The resulting sublist will contain only the last element of the original list:

lastElement = exampleList[-1:][0]
# exampleList[-1:] alone will return the sublist - [6]
# exampleList[-1:][0] will return the last element - 6
print("Last element: ", lastElement)

print("exampleList: ", exampleList)

Which outputs:

Last element:  6
exampleList:  [1, 2, 'Three', ['Four', 5], 6]

The slicing method is only used to access elements of the list and to create a new list using them — without performing any changes to the original list.

Using the Reverse Iterator

Python has two built-in functions that we will use in this method — reversed() and next().

reversed() accepts a list as an argument and returns the reverse iterator for that list, meaning that the iteration is reversed, starting from the last element all the way to the first element. next() accepts an iterator and returns the next element from the iterator:

reversedIterator = reversed(exampleList)

lastElement = next(reversedIterator)
print("Last element: ", lastElement)

Which outputs:

Last element:  6
exampleList:  [1, 2, 'Three', ['Four', 5], 6]

The reversed iterator method is only used to access elements of the list in reverse order — without performing any changes to the original list.

Using the reverse() Method

The reverse() method is used to reverse the elements of the list. It does not take any arguments and does not return any value, instead, it reverses the original list in-place. This means that we can reverse the list and access the new first element:

# Update the original list by reversing its' elements
exampleList.reverse()

# Access the first element of the updated list
lastElement = exampleList[0]
print("Last element: ", lastElement)

print("exampleList: ", exampleList)

Which outputs:

Last element:  6
exampleList:  [6, ['Four', 5], 'Three', 2, 1]

The reverse() method, by definition, does change the original list by reversing the order of its elements. Please keep in mind that this approach may be a really inefficient overkill — since it takes time to reverse a list.

Using itemgetter()

The operator module provides a lot of efficient methods performing all of the fundamental operations in Python, such as the mathematical and logical operations, as well as other object comparison and sequence operations.

The itemgetter() method is one of the many methods in the operator module. It accepts one or more integers as the argument and returns a callable object which can be seen as a type of special function.

When we call operator.itemgetter(0), the resulting object will be a function that will get the first element in a collection. We can also assign a name to that object:

getFirstElement = operator.itemgetter(0)

Now, we can pass in a list to getFirstElement(people), which returns the first element from the list people.

The itemgetter() operator supports negative indexing so retrieving the last element boils down to:

import operator

getLastElement = operator.itemgetter(-1)
lastElement = getLastElement(exampleList)
print("Last element: ", lastElement)

print("exampleList: ", exampleList)

Which outputs:

Last element:  6
exampleList:  [1, 2, 'Three', ['Four', 5], 6]

This approach doesn’t modify the original list — it generates a callable object that accesses it using indices.

Using Loops

Now, a much more manual and rudimentary approach would be using loops. We can iterate through the list, using the length of the list as the final step. Then, when on the len(list)-1 step — we can simply return that item:

for i in range(0, len(exampleList)):
    if i == (len(exampleList)-1) : lastElement = exampleList[i]
        
print("Last element: ", lastElement)
print("exampleList: ", exampleList)

Which outputs:

Last element:  6
exampleList:  [1, 2, 'Three', ['Four', 5], 6]

This also doesn’t change the list at all and simply accesses an element.

Conclusion

There are a lot of ways to get the last element in a list in Python. The main concern when choosing the right way for you is whether or not you want the last element to be removed.

If you need to get the last element without performing any changes to the original list, then the negative indexing method is the clear winner. It is the simplest and most Pythonic way to solve this problem.

On the other hand, if you need to remove the last element, as well as access it, then you should probably go with the pop() method, which is the built-in method for performing exactly this behavior.

Вступление

В этом руководстве мы рассмотрим некоторые из наиболее распространенных
способов найти последний элемент в списке в Python. Сначала мы
рассмотрим самый простой и наиболее питонический способ, а затем
покажем некоторые другие альтернативные решения.

Давайте посмотрим на список, который мы будем использовать:

 exampleList = [1, 2, "Three", ["Four", 5], 6] 

Примечание. Список в Python — это набор элементов, которые не
обязательно одного типа. Один список может содержать элементы, которые
являются числами, строками, вложенными списками и т. Д.

Как получить последний элемент в списке Python

Есть несколько способов получить последний элемент списка в Python —
некоторые из них более интуитивно понятны и практичны, чем другие, а
некоторые из них фактически изменяют исходный список на месте:

  • Использование отрицательной
    индексации — лучший
    подход
  • Использование индексации
  • Использование метода pop()
  • Использование нарезки
  • Использование обратного итератора
  • Использование метода reverse()
  • Использование itemgetter
  • Использование петель

Лучшее решение — использование отрицательной индексации

Python поддерживает понятие отрицательной индексации как метод
доступа к элементам списка. Это означает, что мы можем получить доступ к
элементам в обратном порядке , используя оператор []

Как работает индексация в списках, хорошо известно:

 firstElement = exampleList[0] 
 nthElement = exampleList[n-1] 
 ... 

Первый элемент имеет индекс 0 , второй имеет индекс 1 , а n й
элемент имеет индекс n-1 .

Отрицательная индексация следует той же логике, но в обратном порядке.
Последний элемент имеет индекс -1 , предпоследний элемент имеет индекс
-2 и так далее:

 lastElement = exampleList[-1] 
 print("Last element: ", lastElement) 
 
 print("exampleList: ", exampleList) 
 
 secondToLast = exampleList[-2] 
 print("Second to last element: ", secondToLast) 

Какие выходы:

 Last element: 6 
 exampleList: [1, 2, 'Three', ['Four', 5], 6] 
 Second to last element: ['Four', 5] 

Отрицательная индексация не изменяет исходный список. Это всего лишь
способ доступа к элементам без каких-либо изменений в исходном списке.

Это, безусловно, самое простое и наиболее подходящее для Python решение.

Использование индексации

Простая индексация обычно используется для доступа к элементам в списке
в исходном порядке с помощью оператора [] Как описано выше, первый
элемент имеет индекс 0 , второй элемент имеет индекс 1 и так далее.
Зная это, мы можем сделать вывод, что последний элемент имеет индекс
len(exampleList)-1 :

 lastElement = exampleList[len(exampleList)-1] 
 print("Last element: ", lastElement) 
 
 print("exampleList: ", exampleList) 
 
 secondToLast = exampleList[len(exampleList)-2] 
 print("Second to last element: ", secondToLast) 

Какие выходы:

 Last element: 6 
 exampleList: [1, 2, 'Three', ['Four', 5], 6] 
 Second to last element: ['Four', 5] 

Помимо отрицательной индексации, метод индексации используется только
для доступа к элементам списка без внесения каких-либо изменений в
исходный список.

Использование метода pop ()

В Python метод pop() используется для удаления последнего элемента
данного списка и возврата удаленного элемента.

Метод pop() может дополнительно принимать целочисленный аргумент.
Это индекс элемента, который мы хотим удалить, поэтому, если мы
вызовем exampleList.pop(0) , первый элемент будет удален и
возвращен.

Если аргумент — отрицательное число, будет выполнена логика
отрицательной индексации, чтобы определить, какой элемент удалить.
Вызов exampleList.pop(-1) приведет к удалению последнего элемента
examleList .

Хотя, поскольку метод pop() по умолчанию уже выталкивает последний
элемент
, нет никакой реальной необходимости использовать индексацию:

 lastElement = exampleList.pop() 
 print("Last element: ", lastElement) 
 
 print("exampleList: ", exampleList) 

Какие выходы:

 Last element: 6 
 exampleList: [1, 2, 'Three', ['Four', 5]] 

Обратите внимание, что метод pop() по определению изменяет исходный
список
, удаляя всплывающий элемент.

Использование нарезки

В Python нотация срезов используется для получения подсписка списка.
Сама запись довольно проста:

 exampleList[startIndex:[endIndex[:indexStep]]] 

Это означает, что мы можем получить exampleList с индексами, начиная с
startIndex , вплоть до endIndex с шагом indexStep .

endIndex и indexStepнеобязательные аргументы. Если мы оставим
поле endIndex пустым, его значение по умолчанию будет концом исходного
списка. Значение по умолчанию для indexStep1 .

Если у нас есть список l=['a', 'b', 'c', 'd', 'e'] и нарезать его,
используя l[1:3] результирующий подсписок будет ['b', 'c', 'd'] .
Это означает, что мы выбираем элементы lits l с индексами
1, 2, and 3 .

l[0:4:2] вернет подсписок, содержащий только элементы с четными
индексами — 0, 2, 4 .

Ключевой особенностью нотации срезов, которую мы будем использовать,
является то, что она поддерживает отрицательную индексацию.

Это означает, что l[-1:] можно интерпретировать как: получить все
элементы в списке l , от последнего элемента до конца списка l
.
Результирующий подсписок будет содержать только последний элемент
исходного списка:

 lastElement = exampleList[-1:][0] 
 # exampleList[-1:] alone will return the sublist - [6] 
 # exampleList[-1:][0] will return the last element - 6 
 print("Last element: ", lastElement) 
 
 print("exampleList: ", exampleList) 

Какие выходы:

 Last element: 6 
 exampleList: [1, 2, 'Three', ['Four', 5], 6] 

Метод нарезки используется только для доступа к элементам списка и для
создания нового списка с их помощью — без внесения каких-либо изменений
в исходный список.

Использование обратного итератора

Python имеет две встроенные функции, которые мы будем использовать в
этом методе — reversed() и next() .

reversed() принимает список в качестве аргумента и возвращает обратный
итератор для этого списка, что означает, что итерация отменяется,
начиная с последнего элемента до первого элемента. next() принимает
итератор и возвращает следующий элемент из итератора:

 reversedIterator = reversed(exampleList) 
 
 lastElement = next(reversedIterator) 
 print("Last element: ", lastElement) 

Какие выходы:

 Last element: 6 
 exampleList: [1, 2, 'Three', ['Four', 5], 6] 

Обратный метод итератора используется только для доступа к элементам
списка в обратном порядке — без внесения каких-либо изменений в исходный
список.

Использование метода reverse ()

Метод reverse() используется для переворота элементов списка . Он
не принимает никаких аргументов и не возвращает никакого значения,
вместо этого он меняет исходный список на место . Это означает, что мы
можем перевернуть список и получить доступ к новому первому элементу:

 # Update the original list by reversing its' elements 
 exampleList.reverse() 
 
 # Access the first element of the updated list 
 lastElement = exampleList[0] 
 print("Last element: ", lastElement) 
 
 print("exampleList: ", exampleList) 

Какие выходы:

 Last element: 6 
 exampleList: [6, ['Four', 5], 'Three', 2, 1] 

Метод reverse() по определению изменяет исходный список, меняя порядок
его элементов. Имейте в виду, что такой подход может оказаться
действительно неэффективным излишеством, так как для переворота списка
требуется время.

Использование itemgetter ()

Модуль operator предоставляет множество эффективных методов,
выполняющих все основные операции в Python, такие как математические и
логические операции, а также другие операции сравнения объектов и
последовательности.

Метод itemgetter() — один из многих методов в модуле operator Он
принимает одно или несколько целых чисел в качестве аргумента и
возвращает вызываемый объект, который можно рассматривать как тип
специальной функции.

Когда мы вызываем operator.itemgetter(0) , результирующий объект будет
функцией, которая получит первый элемент в коллекции. Мы также можем
присвоить этому объекту имя:

 getFirstElement = operator.itemgetter(0) 

Теперь мы можем передать список в getFirstElement(l) , который
возвращает первый элемент из списка l .

Оператор itemgetter() поддерживает отрицательную индексацию,
поэтому получение последнего элемента сводится к следующему:

 import operator 
 
 getLastElement = operator.itemgetter(-1) 
 lastElement = getLastElement(exampleList) 
 print("Last element: ", lastElement) 
 
 print("exampleList: ", exampleList) 

Какие выходы:

 Last element: 6 
 exampleList: [1, 2, 'Three', ['Four', 5], 6] 

Этот подход не изменяет исходный список — он генерирует вызываемый
объект, который обращается к нему с помощью индексов.

Использование петель

Теперь гораздо более ручной и элементарный подход будет использовать
циклы. Мы можем перебирать список, используя длину списка в качестве
последнего шага. Затем, на len(l)-1 мы можем просто вернуть этот
элемент:

 for i in range(0, len(exampleList)): 
 if i == (len(exampleList)-1) : lastElement = exampleList[i] 
 
 print("Last element: ", lastElement) 
 print("exampleList: ", exampleList) 

Какие выходы:

 Last element: 6 
 exampleList: [1, 2, 'Three', ['Four', 5], 6] 

Это также не меняет список вообще, а просто получает доступ к элементу.

Заключение

Есть много способов получить последний элемент в списке в Python.
Основное беспокойство при выборе правильного для вас способа — погода
или нет, вы хотите, чтобы последний элемент был удален.

Если вам нужно получить последний элемент без внесения каких-либо
изменений в исходный список, то метод отрицательной индексации
является явным победителем. Это самый простой и самый питонический
способ решить эту проблему.

С другой стороны, если вам нужно удалить последний элемент, а также
получить к нему доступ, вам, вероятно, следует использовать метод
pop()
, который является встроенным методом для выполнения именно
этого поведения.

Понравилась статья? Поделить с друзьями:
  • Как найти своих клиентов на массаж
  • Привет как найти девушку
  • Как составить административный протокол по побоям
  • Как найти плотность в химии задачи
  • Как найти свое видео reels